Slide 1

Slide 1 text

GENERAL QUESTIONS • Can I do different achievements during the meetings? • E.g. Class diagram + Domain modelling achievements? • YES • Tip: Usually up to ~6 achievements per meeting (constraint: time 30 - 45 min)

Slide 2

Slide 2 text

PREVIOUSLY IN ASD… • Structured modelling • UML: Class diagrams • Identify responsibilities • Generalisation / code re-use • Behaviour modelling • Capture interaction between objects • Sequence diagrams vs Communication diagrams

Slide 3

Slide 3 text

ADVANCED SOFTWARE DESIGN LECTURE 5 GRASP Kiko Fernandez

Slide 4

Slide 4 text

TODAY’S LECTURE We will discuss and apply the GRASP design patterns. These provide principles for evaluating and improving designs.

Slide 5

Slide 5 text

WARM UP

Slide 6

Slide 6 text

WHAT IS GOOD DESIGN?

Slide 7

Slide 7 text

GOOD DESIGN: DESIGN THAT COPES WITH CHANGE.

Slide 8

Slide 8 text

EMBRACE CHANGE

Slide 9

Slide 9 text

HOW CAN WE TELL WHETHER A DESIGN IS GOOD?

Slide 10

Slide 10 text

BAD ARCHITECTURE Information Analysis Client Ricoh Colour Scanner Kodak Photo Printer Sybase DB HP High-Res Scanner Xerox Colour Printer Oracle DB Information Retrival Client Document Processing Client Clients Services

Slide 11

Slide 11 text

IMPROVED DESIGN Client Trader Input Device Output Device Information Source uses exchanges with uses uses uses

Slide 12

Slide 12 text

ASSUME THAT YOUR DESIGN IS IMPERFECT

Slide 13

Slide 13 text

GOOD DESIGN Good design is not an absolute! Good design is design that copes with change.

Slide 14

Slide 14 text

ROLE OF DESIGN EVALUATION Improve design – if incorporated into design process. Provide advice for potential implementors – if done after design.

Slide 15

Slide 15 text

APPROACHES Metrics – class width, hierarchy depth Heuristics Checks of pattern usage Design critiques, similar to art criticism or reviews

Slide 16

Slide 16 text

CODE REVIEW (GITHUB)

Slide 17

Slide 17 text

CODE REVIEW (GITHUB)

Slide 18

Slide 18 text

WHAT IF I DON’T… • Do code reviews and/or Create a flexible design

Slide 19

Slide 19 text

WHAT IF I DON’T… • Do code reviews and/or Create a flexible design Facebook case study

Slide 20

Slide 20 text

REAL-WORLD CASE • iOs app • 400+ devs contributing • 16000+ classes • Design problem?

Slide 21

Slide 21 text

REAL-WORLD CASE • iOs app • 400+ devs contributing • 16000+ classes • Design problem? http://www.slideshare.net/quellish/simon-whitaker http://www.darkcoding.net/software/facebooks-code-quality-problem/

Slide 22

Slide 22 text

REAL-WORLD CASE • iOs app • 400+ devs contributing • 16000+ classes • Design problem? Git & Xcode http://www.slideshare.net/quellish/simon-whitaker http://www.darkcoding.net/software/facebooks-code-quality-problem/

Slide 23

Slide 23 text

REAL-WORLD CASE • iOs app • 400+ devs contributing • 16000+ classes • Design problem? Git & Xcode http://www.slideshare.net/quellish/simon-whitaker http://www.darkcoding.net/software/facebooks-code-quality-problem/ Anti-pattern: Functional Decomposition

Slide 24

Slide 24 text

GRASP General Responsibility Assignment Software Patterns or Principles (GRASP) A collection of patterns/principles for achieving good design – patterns of assigning responsibility. Refer to software objects not domain objects.

Slide 25

Slide 25 text

LIST OF GRASP PATTERNS Low coupling High cohesion Creator Information expert Controller Polymorphism Indirection Pure fabrication Protected variations

Slide 26

Slide 26 text

LOW COUPLING

Slide 27

Slide 27 text

COUPLING • An element with weak low (or weak) coupling is not dependent on too many other elements. • Measure how strongly one element is connected to, has knowledge of or relies on other elements.

Slide 28

Slide 28 text

LOW COUPLING Problem: How to reduce the impact of change? Advice: Assign responsibilities so that (unnecessary) coupling remains low.

Slide 29

Slide 29 text

LOW COUPLING Problem: How to reduce the impact of change? Advice: Assign responsibilities so that (unnecessary) coupling remains low.

Slide 30

Slide 30 text

LOW COUPLING Problem: How to reduce the impact of change? Advice: Assign responsibilities so that (unnecessary) coupling remains low. may add additional layers of indirection.

Slide 31

Slide 31 text

WHEN ARE TWO CLASSES COUPLED? • Common forms of coupling from TypeX to TypeY: • TypeX has an attribute that refers to a TypeY instance. • A TypeX object calls on services of a TypeY object. • TypeX has a method that references an instance of TypeY (parameter, local variable, return type). • TypeX is a direct or indirect subclass of TypeY. • TypeY is an interface and TypeX implements that interface.

Slide 32

Slide 32 text

SOLUTION • Assign responsibility so that coupling remains low. • Use this principle to evaluate alternatives.

Slide 33

Slide 33 text

EXAMPLE Is this diagram low or high coupled? Composition Aggregation Association Dependency UML Reminder

Slide 34

Slide 34 text

DISCUSSION. • Low coupling encourages designs to be more independent, which reduces the impact of change. • Needs to be considered with other patterns such as Information Expert (later) and High Cohesion. • Subclassing increases coupling – especially considering Domain objects subclassing technical services (e.g., PersistentObject) • High coupling to stable “global” objects is not problematic – to Java libraries such as java.util. • Do not consider patterns in isolation

Slide 35

Slide 35 text

PICK YOUR BATTLES • The problem is not high coupling per se; it is high coupling to unstable elements. • Designers can future proof various aspects of the system using lower coupling and encapsulation, but there needs to be good motivation. • Focus on points of realistic high instability and evolution.

Slide 36

Slide 36 text

HIGH COUPLING

Slide 37

Slide 37 text

HIGH COUPLING Anti-pattern

Slide 38

Slide 38 text

start strop initialise setMode login setStatus beginReviewA refreshConsole load doThis doThat doTheOther etc ... dataList status mode user group dateTime ACL moduleButton1 moduleButton2 moduleButton3 iterator1 iterator2 console etc ... Main Controller Class xPos yPos locPtr buffer ... Image1 xPos yPos locPtr buffer ... Image1 ... Records ... Data1 ... CutFmt ... Figures ... ErrorSet ... Users valueNms rows cols buffer ... Table1 xPos yPos locPtr buffer ... Image1 ANTI-PATTERN: THE BLOB A single class monopolises most of the functionality. Large class, unrelated attributes and functionality. Single controller + simple data-object classes. Migrated (unrefactored) legacy application

Slide 39

Slide 39 text

HIGH COHESION

Slide 40

Slide 40 text

COHESION Problem: How to keep objects focussed, understandable, and manageable, and as a side effect, support Low Coupling? Low Cohesion: • hard to comprehend • hard to reuse • hard to maintain • delicate; constantly affected by change.

Slide 41

Slide 41 text

SOLUTION • Assign responsibility so that cohesion remains high. • Use this to evaluate alternatives.

Slide 42

Slide 42 text

DISCUSSION • Very low cohesion: a class that does two completely different tasks, e.g., database connectivity and RPC. • Low cohesion: a class that has sole responsibility for a complex task in one functional area, e.g., one single interface responsible for all database access. • Moderate cohesion: a lightweight class, solely responsible for a few logically related areas, e.g., Company that knows the employees and the financial details. • High cohesion: a class with moderate responsibilities in one functional area that collaborates with other classes.

Slide 43

Slide 43 text

RULES OF THUMB • For high cohesion, a class must • have few methods • have a small number of lines of code • not do too much work • have high relatedness of code.

Slide 44

Slide 44 text

COUPLING AND COHESION

Slide 45

Slide 45 text

COUPLING AND COHESION • Coupling: Amount of relations between sub-systems • Low coupling general design goal: Independence, supportability • May lead to extra layers of abstraction • Cohesion: Amount of relations within a sub-system • High cohesion general design goal: Reduce complexity • Often a trade-off

Slide 46

Slide 46 text

PROPERTIES OF A GOOD ARCHITECTURE minimises coupling between modules • Goal: modules don’t need to know much about one another to interact • Low coupling makes future change easier maximises cohesion within modules • Goal: the contents of each module are strongly inter-related • High cohesion makes a module easier to understand University of Toronto Department of Computer Science © 2004-5 Steve Easterbrook. This presentation is available free for non-commercial use with attribution under a creative commons license. 4 Coupling and Cohesion  Architectural Building blocks:  A good architecture:  Minimizes coupling between modules:  Goal: modules don’t need to know much about one another to interact  Low coupling makes future change easier  Maximizes the cohesion of each module  Goal: the contents of each module are strongly inter-related  High cohesion makes a module easier to understand module module connector X  Applies also to classes

Slide 47

Slide 47 text

CREATOR

Slide 48

Slide 48 text

CREATOR Problem: Who creates an A? Advice: Assign class B the responsibility to create an instance of class A if one of these is true (the more the better): • B “contains” or compositely aggregates A. • B records A. • B closely uses A. • B has the initialising data for A.

Slide 49

Slide 49 text

DISCUSSION Basic idea is to find a creator that needs to be connected to the created object in any event. Need initialisation data nearby – sometimes requires that it is passed into client. Creator applies to every object.

Slide 50

Slide 50 text

CREATOR Who is in charge of… - creating attachments - creating task status - creating a task

Slide 51

Slide 51 text

CREATOR Who is in charge of… - creating attachments - creating task status - creating a task

Slide 52

Slide 52 text

VARIATIONS Consider a LinkedList. A client creates the objects stored in the list, but the LinkedList object creates the links of the list. For complex construction, or when instance depends upon a specific external value, other options may need to be considered. Who creates a Concrete Factory?

Slide 53

Slide 53 text

INFORMATION EXPERT

Slide 54

Slide 54 text

INFORMATION EXPERT Problem: What is the basic principle to assign responsibilities/functionality to objects? Choose well and design will be easier to understand, maintain, extend, and reuse.

Slide 55

Slide 55 text

SOLUTION Assign responsibility to the information expert – the class that has the information to fulfil the responsibility. Start by clearly stating the responsibility. Next, look to Design Model. If that is not helpful, look to Domain Model and attempt to use (or expand) its classes to inspire the create of design classes.

Slide 56

Slide 56 text

time Sale quantity Sales LineItem description price itemID Product Description 1 * 1..* 1 Described-by Contains EXAMPLE: POS* POS* = Point Of Sale Who should be responsible for knowing the grand total of a sale?

Slide 57

Slide 57 text

RESPONSIBILITIES Design Class Responsibility ProductDescription knows product price SaleLineItem knows line item subtotal Sale knows grand total

Slide 58

Slide 58 text

SOLUTION getTotal() time … Sale getSubtotal() quantity Sales LineItem getPrice() description price itemID Product Description :Sale lineItems[i] : SaleLineItem :ProductDescription getTotal getSubtotal getPrice

Slide 59

Slide 59 text

DISCUSSION Notice that it required information spread across different classes of objects. Partial information experts collaborate in the task. Sometimes other considerations overrule. For instance, should a Sale object save itself in database? If so, then all database code would be scattered across codebase. Information Expert is about responsibilities, not location of data.

Slide 60

Slide 60 text

CONTROLLER

Slide 61

Slide 61 text

CONTROLLER Advice: Assign the responsibility to an object representing one of these choices: •overall “system”, a “root object” •use case within the system Problem: What first object beyond the UI layer receives and coordinates (“controls”) a system operation?

Slide 62

Slide 62 text

CONTROLLER Advice: Assign the responsibility to an object representing one of these choices: •overall “system”, a “root object” •use case within the system Problem: What first object beyond the UI layer receives and coordinates (“controls”) a system operation?

Slide 63

Slide 63 text

MVC UserStory Controller Task Controller routes.rb Group Model Group view

Slide 64

Slide 64 text

MVC

Slide 65

Slide 65 text

DISCUSSION This is simply a delegation pattern – the UI should not contain application logic. Increases potential for reuse and pluggable interfaces. Creates opportunity to reason about state of use case, for example, to ensure that operations occur in a legal sequence.

Slide 66

Slide 66 text

PROBLEM Problem: Bloated Controllers • a single controller that receives all system events, does too much of the work handling events, has too many attributes (duplicating information found elsewhere), etc. Remedies: • Add more controllers. • Design controller so that it primarily delegates the fulfilment of each system operation to other objects. A bloated controller is an example of low cohesion.

Slide 67

Slide 67 text

POLYMORPHISM

Slide 68

Slide 68 text

POLYMORPHISM Problem: How to handle alternatives based on type? How to create pluggable software components?

Slide 69

Slide 69 text

SOLUTION When related alternatives or behaviours vary by type, assign responsibility for the behaviour – using polymorphic operations – to types for which the behaviour varies. Do not test for the type of an object and use conditional logic to perform varying alternatives based on type.

Slide 70

Slide 70 text

NOT POLYMORPHIC

Slide 71

Slide 71 text

POLYMORPHIC…

Slide 72

Slide 72 text

POLYMORPHIC…

Slide 73

Slide 73 text

POLYMORPHIC…ERROR

Slide 74

Slide 74 text

POLYMORPHIC…ERROR Where!?

Slide 75

Slide 75 text

POLYMORPHIC…ERROR Where!?

Slide 76

Slide 76 text

POLYMORPHIC…ERROR Where!? Specific methods cannot be accessed!

Slide 77

Slide 77 text

POLYMORPHIC action() action() +action() —— —

Slide 78

Slide 78 text

DISCUSSION Interfaces or superclasses: • Guideline: use interfaces when you want polymorphism without committing to a particular class hierarchy. • Liskov substitution principle – a value can be replaced by a subtype without changing important properties of program Future-proofing: • if variability at a particular point is very probably, then expend the effort to accommodate flexibility. • Avoid adding flexibility just because it is possible.

Slide 79

Slide 79 text

EXAMPLE Can we improve the current diagram with polymorphism?

Slide 80

Slide 80 text

EXAMPLE

Slide 81

Slide 81 text

INDIRECTION

Slide 82

Slide 82 text

INDIRECTION Problem: How to assign responsibility to avoid direct coupling between two (or more) things? How to decouple objects so that low coupling is supported and reuse potential remains higher?

Slide 83

Slide 83 text

SOLUTION Assign the responsibility to an intermediate object to mediate between other components or services so that they are not directly coupled. The intermediary creates indirection between the other components.

Slide 84

Slide 84 text

EXAMPLE The adaptor acts as a level of indirection to external systems. Adapter pattern

Slide 85

Slide 85 text

PURE FABRICATION

Slide 86

Slide 86 text

PURE FABRICATION What objects should have the responsibility, when you do not want to violate High Cohesion and Low Coupling, or other goals, but solutions offered by Information Expert (for example) are not appropriate?

Slide 87

Slide 87 text

IN DETAIL Even though classes often correspond to real-world domain objects, there are often cases where assigning responsibility to domain layer software classes leads to problems in terms of poor cohesion or coupling, or low reuse potential.

Slide 88

Slide 88 text

SOLUTION Assign a highly cohesive set of responsibilities to a convenience class, not representing a problem domain concept. Fabrication – made up. Pure – keep it clean: high cohesion, low coupling. “Pure fabrication” – English idiom that implies making something up. Most classes not appearing in the domain model will be pure fabrications.

Slide 89

Slide 89 text

EXAMPLE Need to save Sale instances in a relation database. Information Expert says assign functionality to Sale. Implications: • Task needs large number of supporting database-oriented operations, none related to the concept of a Sale. Incohesion! • Sale becomes coupled to database interface, coupling goes up. • Saving objects in a database is a general task – many classes will need it.

Slide 90

Slide 90 text

SOLUTION insert( Object ) update( Object ) PersistentStorage Understandable concept. Pure software concept. Not in domain model. Sale unaffected. Cohesive concept. Generic and reusable. Alternatives: (Page 612 Larman, 3rd Edition) Chapter 37: Designing a Persistence Framework with Patterns

Slide 91

Slide 91 text

PROTECTED VARIATIONS

Slide 92

Slide 92 text

Problem: How to design objects, subsystems, and systems so that the variations or instability in these elements does not have an undesirable impact on other elements? PROTECTED VARIANTS

Slide 93

Slide 93 text

SOLUTION Identify points of predicted variation or instability Assign responsibilities to create a stable interface around them. “Interface” in broadest sense – not just Java interface. Information hiding!!!

Slide 94

Slide 94 text

EXAMPLE getTaxes( Sale ) : List TaxMasterAdapter getTaxes( Sale ) : List GoodAsGoldTaxProAdapter getTaxes( Sale ) : List «interface» ITaxCalculatorAdapter getTaxes( Sale ) : List ShonkyTaxFraudAdapter The ITaxCalculatorAdaptor interface (from Polymorphism) allows for future tax calculators that may not yet have been thought of.

Slide 95

Slide 95 text

OTHER APPROACHES TO PROTECTED VARIATIONS Core protected variation mechanisms: data encapsulation, interfaces, polymorphism, standards, virtual machines, operating systems. Service lookup: clients look up server with stable interface via technology such as Java JINI or REST for Web services. Law of Demeter: objects never talk to objects they are not directly connected to.

Slide 96

Slide 96 text

CONCLUSION • GRASP: • basic design principles • use throughout any software project • If in doubt, try to apply them • No silver bullet • You will learn more complex patterns

Slide 97

Slide 97 text

NEXT LECTURE • Architectural patterns