COMP2511

24T2 Week 9

Thursday 6PM - 9PM (H18A)

 

Slides by Alvin Cherk (z5311001)

This week

  • Finding Patterns
  • Code and Design Smells
  • Template Pattern
  • Decorator Pattern

assignment-ii: No blogs, no marks. (Including access, layout, MRs).

 

Week 10 Tute: Kahoot & Revision. Email Tina if you want to cover anything specifc.

Week 10 Lab: Sample Exam dry-run using exam environment

MyExperience

Group Task

Finding patterns

Finding Patterns

In groups, determine a possible pattern that could be used to solve each of the following problems:

 

  1. Sorting collections of records in different orders.
    • Strategy
  2. Modelling a file system
    • Composite
  3. Updating a UI component when the state of a program changes
    • Observer
  4. Parsing and evaluating arithmetic expressions
    • Composite
  5. Adjusting the brightness of a screen based on a light sensitivity
    • Observer

Group Task

Code and Design Smells

Code and Design Smells

Mark, Bill and Jeff are working on a PetShop application. The PetShop has functionality to feed, clean and exercise different types of animals.

Mark notices that each time he adds a new species of animal to his system, he also has to rewrite all the methods in the PetShop so it can take care of the new animal.

What code or design smell is present here?

  • Code smell - Divergent change
  • Design problem - Open Closed Principle, high coupling

Code and Design Smells

public class Person {
    private String firstName;
    private String lastName;
    private int age;
    private int birthDay;
    private int birthMonth;
    private int birthYear;
    private String streetAddress;
    private String suburb;
    private String city;
    private String country;
    private int postcode;
    public Person(String firstName, String lastName, 
    			  int age, int birthDay, int birthMonth,
                  int birthYear, String streetAddress,
                  String suburb, String city, String country,
                  int postcode) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.birthDay = birthDay;
        this.birthMonth = birthMonth;
        this.birthYear = birthYear;
        this.streetAddress = streetAddress;
        this.suburb = suburb;
        this.city = city;
        this.country = country;
        this.postcode = postcode;
    }
    // Some various methods below...
}

What code or design smell is present here?

Data clumps & long parameter list

How would you refactor to fix this?

  • Refactor by making more classes for birthday and address (Extract Class / Introduce Parameter Object)
  • Design problem - DRY and KISS

 

If some of the input was "optional" builder pattern may be useful here

Code and Design Smells

public class MathLibrary {
    List<Book> books;

    int sumTitles {
        int total = 0
        for (Book b : books) {
            total += b.title.titleLength;
        }
        return total;
    }
}

public class Book {
    Title title; // Our system just models books
                 // as titles (content doesn't matter)
}

public class Title {
    int titleLength;

    int getTitleLength() {
        return titleLength;
    }

    void setTitleLength(int tL) {
        titleLength = tL;
    }
}

What code or design smell is present here?

  • Inappropriate intimacy (accessing public fields)
  • Message chains - students might bring up Law of Demeter here
  • Data classes/Lazy classes Design smell - High coupling, from encapsulation being broken

How would you refactor to fix this?

  • Make things private
  • Delete the classes and represent titles as strings

Code and Design Smells

How do these code smells cause problems when developing code?

  • Reusability
  • Maintainability
  • Extensibility

How fast does it take for a new developer to understand what is happening? Is behaviour predictable, reasonable and uniform?

Is a code smell always emblematic of a design problem?

No

  • Switch statements & comments are often listed as code smells, but are aren't always 'a problem'

Template Pattern

Template Pattern

What kind of design pattern is it?

Behavioural

  • Template method pattern defines a skeleton (structure) of a behaviour.
  • The template method calls primitive operations, that could be implemented by subclasses OR has default implementations in abstract super class.
  • Subclasses can redefine only certain parts of the behaviour without changing the other parts of the structure.
  • Primitive operations: Operations that have default implementations, or must be implemented by subclass
  • Final operations: Concrete operations that cannot be overriden
  • Hook operations: Concrete operations that do nothing by default and can be redefined by subclass if necessary. This gives the subclass the ability to "hook into" the algorithm at various points

Template vs Strategy

  • Template method works at the class level, so its static
  • Strategy works on the object level, letting you switch behaviours at run-time
  • Template method is based on inheritance: Alter parts of the algorithm by extending those parts in subclasses
  • Strategy is based on composition: You alter parts of the object's behaviour by supplying it with a different strategy
  • Strategy can change their behaviour after creation (supply with new behaviour), templates cannot change behaviour after construction

Decorator Pattern

Decorator Pattern

What kind of design pattern is it?

Structural

  • Adds functionality to a class at run-time. Used when subclassing would result in an exponential rise in new classes
  • Attaches additional responsibilities to an object dynamically
  • Avoids implementing all possible functionality in one complex class
  • Prefers composition over inheritance

 

Adding behaviour to an object, without opening the object up (i.e., rewriting its contents) and changing it.

Decorator Pattern

  • Client: refers to component interface
  • Component: defines a common interface for Component1 and Decorator objects
  • Component1: Defines an object that gets decorated
  • Decorator: maintains a reference to a Component object, and forwards requests to this component object (component.operation())
  • Decorator1, Decorator2, ...: implement additional functionality (addBehaviour() to be performed before and/or after forwarding a request)

Decorator Pattern

public interface Component {
  void doOperationA();
  void doOperationB();
}

public class ConcreteComponent implements Component {
  @Override
  void doOperationA();

  @Override
  void doOperationB();
}

public abstract class Decorator implements Component {
  private Component cc;
}

public class ConcreteDecoratorX extends Decorator {}

COMP2511 Week 9 24T2

By kuroson

COMP2511 Week 9 24T2

  • 105