Patterns
Patterns Pattern-based engineering: in the field of (building) architecting and other disciplines from 1960 s Some software engineers also started to use the concepts Become widely known in SE (Software Engineering) by the book written by the Gang of Four (GoF): Erich Gamma Richard Helm Ralph Johnson John Vlissides
What is a pattern? Christopher Alexander (architect) : Each pattern describes a problem which occurs over and over again in our environment, and then describes the core solution to that problem, in such a way that you can use the solution a million times over, without ever doing it the same way twice (Pattern Language: Towns, Buildings, Construction, 1977) Each pattern is a three-part rule, which expresses a relation between a certain context, a problem, and a solution. As an element in the world, each pattern is a relationship between a certain context, a certain system of forces which occurs repeatedly in that context, and a certain spatial configuration which allows these forces to resolve themselves. (The Timeless Way of Building, 1979)
What is a pattern? Martin Fowler: A pattern is an idea that has been useful in one practical context and will probably be useful in others. (Analysis Patterns: Reusable Object Models, 1997)
What is a pattern? Scott W. Ambler: A pattern is a description of a general solution to a common problem or issue from which a detailed solution to a specific problem may be determined. (http://www.ambysoft.com/processpatternspage.h tml)
Classification of patterns Patterns can exist at all scales. C. Alexander 1. Analyis patterns 2. Architectural patterns/styles 3. Design patterns 4. Programming idioms/implementation patterns 5. Testing patterns 6. Process patterns 7. Antipatterns
Classification of patterns Patterns can exist at all scales. C. Alexander 1. Analyis patterns 2. Architectural patterns/styles 3. Design patterns 4. Programming idioms/implementation patterns 5. Testing patterns 6. Process patterns 7. Antipatterns
Classification of patterns 1. Analyis patterns They follow the conceptual structure of business processes They are groups of concepts representing often used constructions in business modeling What are they used for? They offer design patterns and solutions for frequent problems in order to make it easier to a design model from the analysis model. They help to get abstract analysis models as soon as possible. These models describe the most important specifications of the exyct problem. http://martinfowler.com/tags/analysis%20patterns.html
Examples of analysis patterns Range Quantity For representing value ranges For representing dimensioned values with an amount and a unit together start: <T> end: <T> Range<T> includes(<t>) Quantity amount: Number unit: Unit +, -, *, /, <, >, = x : Range<Integer> start = 10 end = 16 t16 : Quantity amount = 16 unit = ton
Classification of patterns Patterns can exist at all scales. C. Alexander 1. Analyis patterns 2. Architectural patterns/styles 3. Design patterns 4. Programming idioms/implementation patterns 5. Testing patterns 6. Process patterns 7. Antipatterns
Classification of patterns 2. Architectural patterns/styles They contain best practices and pre-defined subsystems for the basic structure of a software structure. E.g.: client/server architecture, distributed object architecture, layered architecture, etc. M. Fowler: Patterns of Enterprise Application Architectures, 2002 F. Buschmann, K. Henney, D.C. Schmidt: Pattern-Oriented Software Architecture, Vol. 1 5., 1996, 2000, 2004, 2007.
Example of an architectural style Name: Model View Contrroller (MVC) Context: interactive applications with a flexible human-machine interface Problem: frequent change requests for user interfaces The same information is to be displayed differently (e.g., bar chart, pie chart) Presentation and behavior of the application should immediately reflect data manipulation User Interfaces that can be changed dinamically (even in run-time) are needed Support of various look-and-feel standards are needed Porting an application should not affect the core functionalities Solution: model encapsulates data and functionality and is independent from the input behavior and the representation of the output; view displays information; controller receives and transforms the input to service requests (towards model and view).
Structure
Architectural style sample Model View Controller (MVC) View represents the display of the model on a user interface. Controller receives user inputs, handles the model and asks the view to refresh accordingly. View Controller Model Model is a nonvisual object representing some information of the problem domain.
View Controller MVC It role is twofold: Separate information display from the model (data) View depends on the model! Contrary it is not true! Users want the same data displayed differently (based on the environment) Model Separate views and controllers Classic example: an editable and a non-editable controller for the same view In practice, we have 1 controller per 1 view in the most of the cases
Classification of patterns Patterns can exist at all scales. C. Alexander 1. Analyis patterns 2. Architectural patterns/styles 3. Design patterns 4. Programming idioms/implementation patterns 5. Testing patterns 6. Process patterns 7. Antipatterns
Classification of patterns 3. Design patterns GoF: Design Patterns: Elements of Reusable Object- Oriented Software, Addison-Wesley, 1994 A. Holub: Holub on Patterns Learning Design Patterns by Looking at Code, Apress, 2004 S. Metsker: Design Patterns Java Workbook, Addison-Wesley, 2002 S. Metsker: Design Patterns in C#, Addison-Wesley, 2004
Classification of patterns 3. Design patterns Sub-systems of a software architecture usually build up a smaller units. These can be described by design patterns. Mid-level patterns: they are smaller than architectural patterns but they do not depend on a programming language or paradigm. They use do not affect the basic structure of the software-system but they highly affect the structure of the sub-system.
Design pattern sample Singleton Goal: allow the instantiation of a class to produce one and only one instance.
Design patterns (GoF) Creational patterns Structural patterns Behavioral patterns
Creational patterns Factory Method It provides an interface to create an object but it lets the subclasses to decide which class is instantiated. Abstract Factory Prototype Builder Singleton
Creational patterns Factory Method Abstract Factory It provides an interface to create a family of objects that are connected or depend on each other without defining the exact classes. Prototype Builder Singleton
Creational patterns Factory Method Abstract Factory Prototype By providing a prototype instance it defines what type of objects are to be created. The object are copies of this prototype. Builder Singleton
Creational patterns Factory Method Abstract Factory Prototype Builder It makes the creation of complex objects independent of their representation. As a result with the same process we can create different representations. Singleton
Creational patterns Factory Method Abstract Factory Prototype Builder Singleton It lets only one instance to be created from a class. For this it provides a global acces point.
Structural patterns Adapter It converts the interface of a class to the interface that can be used by other classes. Facade Proxy Bridge Decorator Flyweight Composite
Structural patterns Adapter Facade In a sub-system it provides a main interface that gathers a set of other interfaces. Proxy Bridge Decorator Flyweight Composite
Structural patterns Adapter Facade Proxy A given object is replaced by another one that overrides the access to the original object. Bridge Decorator Flyweight Composite
Structural patterns Adapter Facade Proxy Bridge It separates the abstract representation from the implementation so that they can be modified separately. Decorator Flyweight Composite
Structural patterns Adapter Facade Proxy Bridge Decorator Adds more additional responsibilities to classes dinamically. Can be used as an alternative of subclasses. Flyweight Composite
Structural patterns Adapter Facade Proxy Bridge Decorator Flyweight Support the use of high mass granular objects. Composite
Structural patterns Adapter Facade Proxy Bridge Decorator Flyweight Composite It orders the objects into a tree structure in order to represent the part-whole relations.
Behavioral patterns Template Method It provides the skeleton of the algorithm of a given method while letting the subclasses the implement the steps. Strategy Observer Mediator State Interpreter Visitor Command Iterator Memento Chain of Responsibility
Behavioral patterns Template Method Strategy Defines an algorithm family in which the algorithms are collected to separate units making it able to replece them by each other. Observer Mediator State Interpreter Visitor Command Iterator Memento Chain of Responsibility
Behavioral patterns Template Method Strategy Observer Provides a connection between objects so that if an object changes all other objects depending on it are informed about that. Mediator State Interpreter Visitor Command Iterator Memento Chain of Responsibility
Behavioral patterns Template Method Strategy Observer Mediator It defines an object that controls the cooperation of a a set of objects. State Interpreter Visitor Command Iterator Memento Chain of Responsibility
Behavioral patterns Template Method Strategy Observer Mediator State It lets the object to change its behavior by changing its inner state. Interpreter Visitor Command Iterator Memento Chain of Responsibility
Behavioral patterns Template Method Strategy Observer Mediator State Interpreter Represents the grammer of a given language. Visitor Command Iterator Memento Chain of Responsibility
Behavioral patterns Template Method Strategy Observer Mediator State Interpreter Visitor It represents an operation that can be executed on the elements of an object structure. Command Iterator Memento Chain of Responsibility
Behavioral patterns Template Method Strategy Observer Mediator State Interpreter Visitor Command It closes queries to an object in order to make it possible to give these queries as parameters to other agents. Iterator Memento Chain of Responsibility
Behavioral patterns Template Method Strategy Observer Mediator State Interpreter Visitor Command Iterator It provides a sequential access to elements of complex objects. Memento Chain of Responsibility
Behavioral patterns Template Method Strategy Observer Mediator State Interpreter Visitor Command Iterator Memento It saves the state of an object without braking encapsulation. Chain of Responsibility
Behavioral patterns Template Method Strategy Observer Mediator State Interpreter Visitor Command Iterator Memento Chain of Responsibility We form a chain from objects that can handle calls. The call goes in the chain while it reaches an object that can handle it.
Classification of patterns Patterns can exist at all scales. C. Alexander 1. Analyis patterns 2. Architectural patterns/styles 3. Design patterns 4. Programming idioms/implementation patterns 5. Testing patterns 6. Process patterns 7. Antipatterns
Classification of patterns 4. Programming idioms / Implementation patterns K. Beck: Implementation patterns, Addison-Wesley, 2008 R.C. Martin: Clean Code A Handbook for Agile Software Craftmanship, Prentice Hall, 2008 J. Bloch: Effective Java (2nd ed.), Addison-Wesley, 2008 B. Wagner: Effective C# 50 Specific Ways to Improve Your C# (2nd ed.), Addison-Wesley, 2010 B. Wagner: More Effective C# 50 Specific Ways to Improve Your C# (2nd ed.), Addison-Wesley, 2008
Classification of patterns 4. Programming idioms / Implementation patterns (Programming idioms / Implementation patterns) An idiom is a low-level programming language specific pattern. It describes how to implement components and some spects of the relations between them with the tools of the given language. They include existing programming experience.
Idioms in Java Instead of string concatenation, use StringBuilder/StringBuffer! Whenever overriding equals, hashcode should also be overridden! Provide such an implementation that ensures that objects considered equal give the same hashcode value! This means that if x.equals(y), then x.hashcode() == y.hashcode() It should be contrapositive so if x.hashcode()!= y.hashcode(), then x.equals(y) == false
public final class PhoneNumber { private final short areacode; private final short prefix; private final short linenumber; public PhoneNumber(int areacode, int prefix, int linenumber) { } rangecheck(areacode, 999, "area code"); rangecheck(prefix, 999, "prefix"); rangecheck(linenumber, 9999, "line number"); this.areacode = (short) areacode; this.prefix = (short) prefix; this.linenumber = (short) linenumber; private static void rangecheck(int arg, int max, String name) { if (arg < 0 arg > max) throw new IllegalArgumentException(name +": " + arg); } @Override public boolean equals(object o) { } if (o == this) return true; if (!(o instanceof PhoneNumber)) return false; PhoneNumber pn = (PhoneNumber)o; return pn.linenumber == linenumber && pn.prefix == prefix && pn.areacode == areacode; // PROBLEM! No hashcode method! }
Map<PhoneNumber, String> m = new HashMap<PhoneNumber, String>(); m.put(new PhoneNumber(707, 867, 5309), "Jenny"); System.out.println(m.get(new PhoneNumber(707, 867, 5309))); null / Jenny Add the following method to class PhoneNumber: @Override public int hashcode() { int result = 17; result = 31 * result + areacode; result = 31 * result + prefix; result = 31 * result + linenumber; return result; }
Classification of patterns Patterns can exist at all scales. C. Alexander 1. Analyis patterns 2. Architectural patterns/styles 3. Design patterns 4. Programming idioms/implementation patterns 5. Testing patterns 6. Process patterns 7. Antipatterns
Classification of patterns 5. Testing patterns G. Meszaros: xunit Test Patterns Refactoring Test Code, Addison-Wesley, 2007 Give recipes for testing, e.g.: how to organize test cases (where to put test code), how to provide test data, how to avoid slow tests,
Testing pattern sample Testcase Class per Class (617) How to organize our test methods into test case classes? Test methods testing the same class should be put into a common class.
Classification of patterns Patterns can exist at all scales. C. Alexander 1. Analyis patterns 2. Architectural patterns/styles 3. Design patterns 4. Programming idioms/implementation patterns 5. Testing patterns 6. Process patterns 7. Antipatterns
Classification of patterns 6. Process patterns A collection of techniques and activities that can be used in OO software engeneering process. By the correct use of them the software engeneering process of our organization can be formed. S.W. Ambler: Process Patterns: Building Large-Scale Systems Using Object Technology, SIGS Books/Cambridge University Press, 1998 S.W. Ambler: More Process Patterns: Delivering Large-Scale Systems Using Object Technology, SIGS Books/Cambridge University Press, 1998
OO software development process
Classification of patterns Patterns can exist at all scales. C. Alexander 1. Analyis patterns 2. Architectural patterns/styles 3. Design patterns 4. Programming idioms/implementation patterns 5. Testing patterns 6. Process patterns 7. Antipatterns
Classification of patterns 7. Antipatterns W.J. Brown et al.: AntiPatterns Refactoring Software, Architectures, and Projects in Crisis, John Wiley & Sons, 1998 P.A. Laplante, C.J. Neill: Antipatterns Identification, Refactoring, and Management, Auerbach, 2006
Antipattern categories Software development antipatterns Software architectural antipatterns Project management antipatterns
Software engineering antipattern samples Spaghetti code unstructured code solution: refactoring! Blob