Download
patterns anti patterns refactoring n.
Skip this Video
Loading SlideShow in 5 Seconds..
Patterns Anti-Patterns Refactoring PowerPoint Presentation
Download Presentation
Patterns Anti-Patterns Refactoring

Patterns Anti-Patterns Refactoring

258 Views Download Presentation
Download Presentation

Patterns Anti-Patterns Refactoring

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. PatternsAnti-Patterns Refactoring F28SD2 Software Design Monica FarrowG.30/4160 monica@macs.hw.ac.uk Material on Vision Patterns and anti-patterns

  2. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns What’s their history? • Late 1970s, Christopher Alexander developed a pattern language for the built environment. • http://downlode.org/Etext/Patterns/ • 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. Patterns and anti-patterns An example: 21 Four storey limit • May be part of • 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).

  7. Patterns and anti-patterns An example: 67 Common Land • May be part of • 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).

  8. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns A Conceptual View Abstraction = 1/Specificity Patterns Frameworks Components Libraries/APIs Objects

  13. Patterns and anti-patterns 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. Patterns and anti-patterns Classification of Patterns CREATIONAL PATTERNS Abstract factory Builder Factory method Prototype Singleton STRUCTURAL PATTERNS Adapter Bridge Composite Decorator Facade Flyweight Proxy BEHAVIORAL PATTERNS Chain of responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template method Visitor

  15. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns Singleton • singleton : Singleton • Singleton() + getInstance() : Singleton Singleton class diagram

  19. Patterns and anti-patterns 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. Patterns and anti-patterns 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 privateNextNumber () { number = 0; }

  21. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns Façade and UML Client Façade Class 2 Class 3 Class 1 Class 4 Class 6 Class 5 Class 7

  24. Patterns and anti-patterns 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. Patterns and anti-patterns Iterator pattern class diagram Client <<interface>> Iterator first() next() isDone() currentItem() <<interface>> Aggregate createIterator() ConcreteAggregate Collection of objects createIterator() ConcreteIterator first() next() isDone() currentItem()

  26. Patterns and anti-patterns Iterator and UML :User cs:Customers c1:Customer c2:Customer query(inEdinburgh) c1 :=first() [true] c2 :=next() [false]

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

  28. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns ‘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. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns 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. Patterns and anti-patterns 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!