Presentation is loading. Please wait.

Presentation is loading. Please wait.

31/03/09Patterns and anti-patterns1 Patterns Anti-Patterns Refactoring F28SD2 Software Design Monica Farrow G.30/4160

Similar presentations

Presentation on theme: "31/03/09Patterns and anti-patterns1 Patterns Anti-Patterns Refactoring F28SD2 Software Design Monica Farrow G.30/4160"— Presentation transcript:

1 31/03/09Patterns and anti-patterns1 Patterns Anti-Patterns Refactoring F28SD2 Software Design Monica Farrow G.30/4160 Material on Vision

2 31/03/09Patterns and anti-patterns2 Where do patterns come from? Designing good reusable Object-Oriented Software is hard. The solution should solve your problem, but should be general enough to be reused for the same kind of problem. It's usually impossible to get things right first time. The solution needs refactoring. Refactoring is the action of improving the design of existing code without changing its behaviour: tidying up

3 31/03/09Patterns and anti-patterns3 More on how patterns come about Expert software designers tend to reuse the good designs they’ve created again and again. They don’t want to reinvent a solution to a problem they’ve already solved In the course of time, good and successful designs end up becoming generalised as patterns

4 31/03/09Patterns and anti-patterns4 What is a pattern? Here are several definitions of a design pattern: A general solution to a common problem in software design (not implementation) Best practices of experienced object-oriented software developers Descriptions of communicating objects and classes that are customised to solve a general design problem in a particular context This means a pattern can never be transformed directly into code. It needs to be tailored to a specific problem

5 31/03/09Patterns and anti-patterns5 What’s their history? Late 1970s, Christopher Alexander developed a pattern language for the built environment. He was an architect himself (among other things) and seems to have been reacting to the arrogance and grossness of so much modern architecture (especially in the 60s and 70s). Mediaeval cities, for example, are attractive and harmonious. He tried to discern patterns in architecture that worked, rather than lay down the law according to some architect-centred aesthetic

6 31/03/09Patterns and anti-patterns6 An example: 21 Four storey limit May be part of Magic of the City (10), City Country Fingers (3), Lace of Country Streets (5). Magic of the City (10)City Country Fingers (3)Lace of Country Streets (5) Conflict There is abundant evidence to show that high buildings make people crazy. Resolution In any urban area, no matter how dense, keep the majority of buildings four storeys high or less. It is possible that certain buildings should exceed this limit, but they should never be buildings for human habitation. May contain Number of Stories (96), Density Rings (29), Building Complex (95), Housing Hill (39), High Places (62). Number of Stories (96)Density Rings (29)Building Complex (95)Housing Hill (39)High Places (62)

7 31/03/09Patterns and anti-patterns7 An example: 67 Common Land May be part of Accessible Green (60), House Cluster (37), Row Houses (38), Housing Hill (39), Work Community (41). Accessible Green (60)House Cluster (37)Row Houses (38) Housing Hill (39)Work Community (41) Conflict Without common land no social system can survive. Resolution Give over 25 per cent of the land in house clusters to common land which touches, or is very very near, the homes which share it. Basic: be wary of the automobile; on no account let it dominate this land. May contain South Facing Outdoors (105), Positive Outdoor Space (106), Hierarchy of Open Space (114), Outdoor Room (163), Local Sports (72). South Facing Outdoors (105)Positive Outdoor Space (106) Hierarchy of Open Space (114)Outdoor Room (163)Local Sports (72)

8 31/03/09Patterns and anti-patterns8 And so on to software engineering In the late 1980s, the idea of patterns started to be adopted by programmers. Original catalogue “Design Patterns” by Gamma, Helm, Johnson and Vlissides, Addison -Wesley, 1995 lists 23 standard patterns, their uses, advantages and drawbacks all patterns described in C++ terms Since then, lots of different books have been published, among them Java Design Patterns by James Cooper (2000) Head First Design Patterns by Eric and Elisabeth Freeman (2004)

9 31/03/09Patterns and anti-patterns9 Patterns speed up software development They have been proven Patterns reflect the experience, knowledge and insights of developers who have successfully used these patterns in their own work. They are reusable Patterns provide a ready-made solution that can be adapted to different problems as necessary They create a shift of focus to a higher level of abstraction: pattern level instead of class level We’ve got design building bricks that we know works well. We can therefore work on trying to combine them together instead of focusing on details like “what should be the relation between those 2 classes?”

10 31/03/09Patterns and anti-patterns10 Patterns make maintenance easier They are expressive Patterns provide a common vocabulary of solutions that can express large solutions succinctly for coders and architects familiar with them They improve code readability Classes are clearly defined and the link between them is clear

11 31/03/09Patterns and anti-patterns11 Diverse approaches to re-use Patterns Abstract designs Frameworks concrete, implemented, rather than abstract Components Somewhere between a framework and an object. Class libraries Smaller scope and not domain specific Objects Inheritance

12 31/03/09Patterns and anti-patterns12 ObjectsLibraries/APIsComponentsFrameworksPatterns Abstraction = 1/Specificity A Conceptual View

13 31/03/09Patterns and anti-patterns13 Three categories of pattern Creational Patterns deal with ways to create instances of objects Structural Patterns describe how classes and objects can be combined to form larger structures Behavioural Patterns are concerned with communications between objects Other patterns exist in specific areas such as Concurrency programming

14 31/03/09Patterns and anti-patterns14 Classification of Patterns STRUCTURAL PATTERNS Adapter Bridge Composite Decorator Facade Flyweight Proxy CREATIONAL PATTERNS Abstract factory Builder Factory method Prototype Singleton BEHAVIORAL PATTERNS Chain of responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template method Visitor

15 31/03/09Patterns and anti-patterns15 Singleton Pattern (creational) Use to ensure only one instance of this class in the system, while allowing other classes to get access to this instance. Useful for objects such as printSpoolers and filesystems, which are accessed by various objects in a system For writing to a log file A Window manager An NextNumber manager, providing the next number in a sequence Provides a single point to access it controls access to instance avoids the use of a global variable

16 31/03/09Patterns and anti-patterns16 NextNumber Example The object provides the next number in a sequence Keeps the last number as an instance variable public class NextNumber { private int number; public NextNumber() { this.number = 0; } public int getNext() { number++; return number; }

17 31/03/09Patterns and anti-patterns17 Using NextNumber In this version, a next number object can be created anywhere in the program, using the code below. There is no way of guaranteeing a unique next number. NextNumber nn = new NextNumber(); int next = nn.getNext(); We need to make it impossible for people to create a NewNumber object. Make the constructor private Only allow access through a static method NextNumber nn = NextNumber.getInstance();int next = nn.getNext();

18 31/03/09Patterns and anti-patterns18 Singleton class diagram Singleton - singleton : Singleton - Singleton() + getInstance() : Singleton

19 31/03/09Patterns and anti-patterns19 Singleton (creational) Note that, unusually, the Singleton class contains an instance variable of itself. public class Singleton { private static Singleton instance; //private constructor, access only within class private Singleton () {... } //public getInstance(), accessible everywhere public static Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; }

20 31/03/09Patterns and anti-patterns20 Convert NextNumber to Singleton (1) Merge Singleton class with NextNumber class See this and next slide public class NextNumber { private static NextNumber instance; private int number; //private constructor, //access only within class private NextNumber () { number = 0; }

21 31/03/09Patterns and anti-patterns21 Convert NextNumber to Singleton (2) //public getInstance(), accessible everywhere public static NextNumber getInstance() { if (instance == null) instance = new NextNumber(); return instance; } //NextNumber get method public int getNext() { number++; return number; }

22 31/03/09Patterns and anti-patterns22 Façade (structural) This pattern provides a simplified (or friendly) interface to a complex (or unfriendly) sub- system. e.g. Create a GUI screen without having to worry about collecting and placing all the standard components and features. Or query a database more simply. Allows a simple interface to be fixed even if the underlying implementation changes De-couples the client and the sub-system. Façades are often singletons

23 31/03/09Patterns and anti-patterns23 Façade and UML Client Façade Class 1 Class 2 Class 5 Class 3 Class 7 Class 4 Class 6

24 31/03/09Patterns and anti-patterns24 Iterator (behavioural) This pattern allows us to access the elements of an aggregate object in a sequential manner, without exposing the underlying representation. In general, we need methods for first, next, isDone and currentItem.

25 31/03/09Patterns and anti-patterns25 Iterator pattern class diagram > Aggregate createIterator() > Iterator first() next() isDone() currentItem() ConcreteIterator first() next() isDone() currentItem() ConcreteAggregate Collection of objects createIterator() Client

26 31/03/09Patterns and anti-patterns26 Iterator and UML c1:Customercs:Customersc2:Customer :User query(inEdinburgh) c1 :=first() c2 :=next() [true] [false]

27 31/03/09Patterns and anti-patterns27 Iterator in java You may have met iterators in Java ArrayList myCollection = new ArrayList ();... //create an iterator Iterator it = myCollection.iterator(); while (it.hasNext()) { //get next element MyElement element =; //do some processing with this element element.doMethod(); }

28 31/03/09Patterns and anti-patterns28 ITERATOR PATTERN Java is using the Iterator Pattern This pattern allows us to access the elements of an aggregate object in a sequential manner, without exposing the underlying representation. The original pattern defined methods for createIterator, first, next, isDone and currentItem. Implementations in the java collections framework use iterator(), hasNext(), next() and remove()

29 31/03/09Patterns and anti-patterns29 Pattern Summary Patterns aim to Maximise code reuse Minimise re-implementation Increase cohesion Reduce coupling Projects using patterns are likely to involve an extra layer of classes Extra complexity Easier to modify

30 31/03/09Patterns and anti-patterns30 Anti-patterns An anti-pattern is a common solution that actually has bad features Should provide some suggestion about how to improve the code Anti-patterns don’t just apply to OO design See wikipedia

31 31/03/09Patterns and anti-patterns31 ‘Blob or God class’ OO Anti-pattern One enormous class containing most of actions of code Other classes have only simple get/set type methods Improve by moving operations into correct class It’s often the result of taking procedural design and re- implementing as object oriented E.g. Items class has price and quantity Items class should calculate the total cost = price*quantity, rather than Blob class doing items.getPrice()*items.getQuantity()

32 31/03/09Patterns and anti-patterns32 Other OO Anti-patterns Singletonitis Over-use of the singleton pattern Sequential coupling requires methods to be called in particular order Object orgy Failing to properly encapsulate objects permitting unrestricted access to their internals

33 31/03/09Patterns and anti-patterns33 Programming Anti-patterns Blind faith neglecting to test error returns from methods (in java most error returns are specified as Exceptions) Loop-switch sequence implementing sequential code as a loop statement with a switch to select different actions first time through do A, second time do B etc rather than doA(); doB();

34 31/03/09Patterns and anti-patterns34 More Programming Anti-patterns Accidental complexity often a consequence of early design decisions in prototypes Magic numbers : unexplained numbers in code eg using 7 instead of constant DAYS_IN_WEEK = 7 Magic strings Including literal strings in code for comparisons

35 31/03/09Patterns and anti-patterns35 Refactoring It's usually impossible to get things right first time. The solution needs refactoring. improving the design of existing code without changing its behaviour: tidying up Improvements to code/architecture of code small improvements continually regression tested JUnit framework See later JUnit lecture for CS students

36 31/03/09Patterns and anti-patterns36 Refactoring Over time, maintenance can make code “messy” Rushed implementations can also be “messy” Messy code hinders maintenance Refactoring refreshes/tidies the code without changing functionality, eg... improve cohesion and reduce coupling apply patterns remove anti-patterns optimise performance (speed and memory issues) add comments (perhaps to enable JavaDocs)

37 31/03/09Patterns and anti-patterns37 When to refactor? No precise criteria If you find bad smells - sections of code that have known difficulties (e.g. antipatterns) or are too complex It is a good idea to refactor before adding a new feature or modification

38 31/03/09Patterns and anti-patterns38 Some bad smells Duplicated code extract as method – possibly parameterised, possibly a utility method similar code in related subclasses move common subset of code to superclass as a method subclass specific code can be implemented as overridden methods Long Method if code for a method is too long to understand easily, extract subparts as methods any section of code that needs commenting should be replaced by a method with a meaningful identifier

39 31/03/09Patterns and anti-patterns39 More Bad Smells Feature Envy method uses data mostly from a different class refactor by moving method to the class responsible for most of the data Switch Statements often indicate a “type” field introduction of new types requires every switch statement to be examined and modified consider using inheritance, enums, state pattern….

40 31/03/09Patterns and anti-patterns40 Even more bad smells Data Clumps items of data that are usually used together may lead to long parameter lists (another bad smell) consider introducing a class to hold the related data Comments section of code with an explanatory comment can often be replaced by suitably named method

41 31/03/09Patterns and anti-patterns41 Summary Patterns Tried and tested solution to a common problem You still need to write the code, but you know which classes to use, and how these classes are related. Anti-patterns BAD solution to common problem – recognise and refactor Refactoring Improving the design of the code without altering the functionality Recognises that we don’t usually get things right first time!

Download ppt "31/03/09Patterns and anti-patterns1 Patterns Anti-Patterns Refactoring F28SD2 Software Design Monica Farrow G.30/4160"

Similar presentations

Ads by Google