OO Development 6 - Software Design

  • 11,565 views
Uploaded on

Course material from my Object-Oriented Development course.This presentation covers the design phase and focuses on a variety of software design principles.

Course material from my Object-Oriented Development course.This presentation covers the design phase and focuses on a variety of software design principles.

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
No Downloads

Views

Total Views
11,565
On Slideshare
0
From Embeds
0
Number of Embeds
2

Actions

Shares
Downloads
328
Comments
2
Likes
11

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. 6 DESIGN Examining the software design workflow
  • 2. 1 INTRODUCTION 2 METHODOLOGIES 3 MODELS AND UML 4 OBJECT CONCEPTS 5 ANALYSIS2 6 SOFTWARE DESIGN
  • 3. Our Process3  Reminder of object-oriented development process we are following in this course is that there are four phases:  Inception  Elaboration  Construction  Transition Inception El aborati on Construction Transiti on  Each phase consists of one or more iterations 1 2 3 4 5 6 7 8 of the following workflows: Requirem ents  Requirements Anal y s is  Analysis & Design  Implementation Des i gn  Test  In this section, we are going to examine the Implement ation design workflow principally in the context of the Elaboration and construction phases. T es t
  • 4. Design Workflow4  In the analysis workflow, the requirements are analyzed in more detail, so as to begin the description of the internal structure and behavior of the proposed system.  In the design workflow, we more fully describe and model how the internal structure and behavior will be implemented.  The design workflow is the primary modeling activity of the last part of the elaboration and first half of the construction phases. Source: Arlow and Neustadt, UML and the Unified Process (Addison-Wesley, 2002), p. 249-50.
  • 5. Object-Oriented Design5  Our analysis model defines what we need to build.  It doesn’t define how the system will be build  Object-oriented design determines how to build.  Object-oriented design bridges the gap between analysis and implementation.  In the design phase, you :  add detail about user interface,  specify data storage,  add layers,  re-evaluate the responsibilities spelled out in interaction diagrams,  add detail to class diagrams so as to create design classes, and re- evaluate and  re-factor your initial analysis model using best-practice solutions and heuristic principles called patterns. Source: Bennett, McRobb, and Farmer, Object-Oriented Systems Analysis and Design (McGraw Hill, 2002), p. 301.
  • 6. Analysis versus Design6  The boundary between analysis and design can be quite vague; they often overlap.  Some software processes merge the analysis and design stages.  Inreal iterative projects, after an initial design model is created, the analysis model tends to become redundant and is no longer maintained.  for smaller projects (under 200 classes), the design model may be small enough to be understandable, so a separate analysis model may be unnecessary. Source: Arlow and Neustadt, UML and the Unified Process (Addison-Wesley, 2002), p. 252-3.
  • 7. System Design and Detailed7 Design  Design of systems takes place at two levels:  System design  Also called software architecture design.  Concerned with the overall architecture of the system  Detailed design  Also called class design  Concerned with designing individual components to fit this architecture. Source: Bennett, McRobb, and Farmer, Object-Oriented Systems Analysis and Design (McGraw Hill, 2002), p. 305.
  • 8. What is Software Architecture?8  The system design of an application is also referred to as software architecture.  Software architecture is a shared understanding of a systems design by the developers on a project.  Commonly this shared understanding is in the form of the major components of the system and how they interact.  Two key aspects:  It is the highest-level breakdown of a system into its parts.  It is about early decisions that are hard to change after the system is implemented. Source: Martin Fowler, Patterns of Enterprise Application Architecture (Addison-Wesley, 2003), p. 2.
  • 9. System Design9  In system/architectural design, you define the larger parts of the system and how they relate.  That is, system design is focused on making high-level decisions concerning the overall structure of the system.  This is accomplished by identifying layers (also called sub-systems) and allocating classes to them.
  • 10. Layering10  Layering is perhaps the most common way to architect a software system.  Layering is a way of organizing your software design into groups of classes that fulfill a common purpose. Source: Frank Buschmann et al, A Pattern of Systems (Wiley, 1996), p. 31-51.
  • 11. Layering11  The goal of layering is to distribute the functionality of your software among classes, so that the coupling of a given class is minimized.  While a layer may have dependencies to another layer’s interface, it should be independent of other layers implementation.  We want to avoid having late changes to a class "ripple" (cause changes) to a host of other classes.  Layering can thus increase the modularity (and thus maintainability) of your system.  Different layers can be constructed by different team members. Source: Frank Buschmann et al, A Pattern of Systems (Wiley, 1996), p. 31-51.
  • 12. Layering12  The essential principle of layering is that any element within a layer depends only on other elements "beneath" it.  The top layers typically contain either the most abstraction, or the most variable elements.  Each layer should be loosely coupled to the layers underneath. Layer 4 Layer 3 Layer 2 Layer 1 Source: Eric Evans, Domain-Driven Design (Addison-Wesley, 2003), p. 69.
  • 13. Open versus Closed Architecture13  Layer architectures may be open or closed.  Closed architecture minimizes the dependencies between layers and makes for more independent layers.  That is, each layer is strongly encapsulated. Source: Bennett, McRobb, and Farmer, Object-Oriented Systems Analysis and Design (McGraw Hill, 2002), p. 326.
  • 14. Open versus Closed Architecture14  Open architecture is more efficient but less maintainable due to the increased dependencies.  Theoretically, a closed layer architecture is best, but open-layer architectures are much easier to create. Layer 4 Arrows indicate message flow Layer 4 Layer 3 Layer 3 Layer 2 Layer 2 Layer 1 Layer 1 Closed layer architecture Open layer architecture Source: Bennett, McRobb, and Farmer, Object-Oriented Systems Analysis and Design (McGraw Hill, 2002), p. 326.
  • 15. Common Layer Architectures15 Presentation Presentation Business Logic Application Data Access Domain Three layer architecture Data Access Four layer architecture View Boundary Controller Control Model Entity MVC architecture BCE architecture Source: Bennett, McRobb, and Farmer, Object-Oriented Systems Analysis and Design (McGraw Hill, 2002), p. 328-30.
  • 16. Common Layer Architectures I16  Presentation Layer  Responsible for showing information to the user and interpreting the users commands.  Business Layer  Contains all business logic.  Data Access/Persistence Layer  Responsible for interacting with external data sources. All database related code should reside here. Presentation Business Data Access
  • 17. Common Layer Architectures II17 «boundary»  Boundary ViewCustomerList  Boundary layer refer to any classes that interact directly with the actors.  Should only communicate with Control layer classes  Entity ViewCustomerList  Entity layer contain classes that represent objects in the problem domain. «entity» Customer  Should have no knowledge of Boundary or Control classes.  Control  Control layer classes coordinate between the boundary and entity layers. Customer  Represent the application logic  Often, each use case will have a control class «control» Boundary CustomerListController Control Entity CustomerListController
  • 18. Common Layer Architectures III18  Presentation Layer  Responsible for showing information to the user Presentation and interpreting the users commands.  Application Layer Application  Defines the job the software is supposed to do and directs the domain objects. Domain  Domain Layer Infrastructure  Responsible for representing concepts of the business.  Infrastructure Layer  Provides technical capabilities that support the higher layers (e.g., persistence, web services, general widget drawing, security, etc). Source: Eric Evans, Domain-Driven Design (Addison-Wesley, 2003), p. 70.
  • 19. Common Layer Architectures IV19  Presentation Layer Presentation  Responsible for showing information to the user and interpreting the users commands. Presentation Helper  Presentation Helper Layer  This layer hides all the complexity of the Service application layer and it is adapted to the specific presentation layer implementation . Persistence  Service Layer  The service layer provides a layer of services to Domain the presentation layer that it can use.  Domain Layer  Responsible for representing concepts of the business. This layer focuses on concepts or entities rather than use cases.  Persistence/Data Access Layer  The persistence layer encapsulates the data tier. Source: Jimmy Nilsson, "A Pure Object-Oriented Object Model," www.vb2themax.com
  • 20. Common Layer Architectures V20  UI Component Layer UI Component  Responsible for showing information to the user and interpreting the users commands using UI components (windows forms, web pages, user controls, UI Process etc)  UI Process Layer Business Process Domain Infrastructure  Handles validation and navigation between UI components.  Business Process Layer  Business processes reflect the macro-level activities that the business Data Access Components performs. Examples include order processing, customer support, and procurement of materials. These business processes are encapsulated by business workflow components that orchestrate one or more domain objects Data Access Helper to implement a business process.  Domain/Business Objects Layer  Data Access Components  Data access components isolate the business layer from the details of the specific data storage solution. Each DAC might provide CRUD (create, retrieve, update, and delete) capabilities for its data source.  Data Access Helper  Common helper classes used by the DACs.  Infrastructure Source: Jimmy Nilsson, "A Pure Object-Oriented Object Model," www.vb2themax.com
  • 21. Diagramming Layers21 «layer» «layer» User Interface Controllers «traces» «boundary» «boundary» «boundary» Client List Client Details Portfolio List
  • 22. Class Design22  Concerned with the detailed design of the classes in the layers and their interactions.  The result will be a detailed specification of the attributes and operations of all the classes. Customer Customer -m_name: String Analysis class -m_address: String -m_phone: String #numCustomers: int +getName(): String +getPhone(): String +setName(name: String): void +setPhone(phone: String): void #getNumCustomers(): int Design class
  • 23. Class Design23  The static class diagram is always at the focus of our analysis and design activities, since it indicates what will be implemented.  As part of the analysis phase, one may have created several interaction diagrams for most of the important scenarios in each use case.  As these interaction diagrams are developed, we need to add the behaviors necessary to model the responsibilities in these scenarios.  This may be done as part of the analysis model  Or it may be done now in the design phase
  • 24. Class Design24  A newly-developed system will be extended many times over its life.  Thus,merely designing an implementation that meets current requirements is not sufficient.  The design must be flexible enough to permit extension and reuse. Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 127.
  • 25. Symptoms of Poor Design25  Rigidity  The design is hard to change  Fragility  The design is easy to break  Immobility  The design is hard to reuse  Repetition  The design is only practical using copy and paste Source: Robert C. Martin, Agile Software Development (Prentice Hall, 2003), p. 85.
  • 26. Class Design Principles26  Completeness and Sufficiency  Primitiveness  High Cohesion  Low Coupling
  • 27. Completeness and Sufficiency27  Completeness refers to giving users of a class the services they expect.  Users tend to make assumptions about the services from the name and semantics of a class.  e.g., a Client class will be expected to have methods for accessing/setting a client’s name, while a BankAccount class will be expected to have a Withdrawal method.  Sufficiency refers to the fact all methods of a class are entirely focused on realizing the intent behind the class.  A class should not surprise a user. It should contain the expected methods and no more.  Sufficiency is thus about keeping a class as simple and focused as possible. Source: Arlow and Neustadt, UML and the Unified Process (Addison-Wesley, 2002), p. 261.
  • 28. Primitiveness28  Methods should be designed to offer a single primitive, atomic and unique service. A class should not offer multiple ways of doing the same thing.  Your aim is that classes should make available the simplest and smallest possible set of methods necessary to implement the behavior required by class. BankAccount BadBankAccount +deposit(in value) +deposit(in value) +depositTwice(in value1, in value2) BankAccount ba = new BankAccount(); ba.deposit(300); BadBankAccount ba = new BadBankAccount(); ba.deposit(1200); ba.depositTwice(300, 1200); Yes! No! Source: Arlow and Neustadt, UML and the Unified Process (Addison-Wesley, 2002), p. 262.
  • 29. High Cohesion29  Cohesion is a measure of the diversity of an classs features.  The less diverse its features are, the more cohesive the class.  A highly cohesive class represents a single abstraction / concept / activity / responsibility.  Each class in a design should be as cohesive as possible.  That is, its responsibilities should be as strongly-related and focused as possible.  Cohesive classes are generally easier to understand, reuse and maintain. Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 128.
  • 30. Cohesion30  A class with low cohesion tends to cause these problems:  More difficult to understand  Harder to reuse, and maintain  More possibilities for bugs since more affected by change low cohesion CustomerAccount -accountNo -lastname -firstname How many abstractions does this class contain? -address -balance low cohesion Employee +getName() How many abstractions does this class contain? +getPhone() +printName() +calculatePension() +calculateTax() +displayChildren() +displayBenefits() Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 129.
  • 31. Cohesion31  In classes with low cohesion, there is an assumption that two (or more) abstractions in the class are always in a one-to-one-relationship, which can cause problems later.  Similarto rule against transitive dependencies in database normalization.  You may have to specialize the class along different dimensions based on the different abstractions. CustomerAccount -accountNo -lastname -firstname -address -balance 1 1..* Customer Account Separate the two abstractions
  • 32. Low Cohesion and Inheritance32 Account Inidividual Institutional Cash Account Margin Account Account Account How many abstractions does each subclass contain? Account Inidividual Institutional Cash Account Margin Account Account Account Individual Cash Individual Margin Institutional Cash Institutional Account Account Account Margin Account Problems when we further specialize the classes
  • 33. High Cohesion and Inheritance33 1..* * Customer Account Separate the two abstractions 1..* * Customer Account Inidividual Institutional Cash Account Margin Account Account Account Then specialize the two abstractions
  • 34. Low Coupling34  Coupling is a measure of the interconnectedness of a class to other classes.  That is, coupling occurs when one class depends on another in some way.  The greater the coupling, the greater the interdependence among classes.  When classes are highly coupled, changes in one class affect all the other classes.  As coupling is reduced, a design will become more maintainable and extensible.  “coupling is your worst enemy” [Arlow & Neustadt, p. 263] Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 128.
  • 35. Coupling35 :Menu :House : Room << create >> Menu is coupled to two other classes initialize() :Menu :House : Room << create >> Now Menu is coupled to just one class initialize()
  • 36. Coupling Example36 1: makePayment() 2: addPayment() 3: new() : Register : Sale p : Payment lower coupling 1: makePayment() 2: new() : Register p : Payment higher coupling 3: ad dP ay m en t() : Sale
  • 37. Coupling37  Of course, some coupling is necessary; otherwise the classes don’t interact.  There is no rule for how much coupling is too much.  One thing you can look for is “finger” effects in your sequence diagram (see next slide); better to have “stair” effects.
  • 38. Stair vs Finger in Sequence Diagrams Object1 Object2 Object3 Object4 Object5 Object638 Message1 Message2 Message3 Finger Indicative of high coupling Message4 Message5 Object1 Object2 Object3 Object4 Object5 Object6 Message1 Message2 Message3 Stair Message4 Indicative of low coupling Message5
  • 39. Types of Coupling39  Some of the forms of coupling are:  interaction coupling  identity coupling  representational coupling  subclass coupling Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 133.
  • 40. Interaction Coupling40  A measure of the number of message types an object must send to another object and the number of parameters passed with those messages.  Should try to reduce interaction coupling in order to increase object reusability and to reduce number of potential changes in other classes if a class’s interface changes. MyDataAccess da = new MyDataAccess(); da.setName("wine"); da.setExtension("mdb"); da.setType("Microsoft Access"); * Illustrates high interaction coupling if all these messages da.setDriverAccess("odbc"); must be sent before runSql message da.setDriverType("access"); da.runSql(strSQL, READ_ONLY, READ_FORWARD, DYNAMIC_CURSOR, REPLICATION_ON, LOGGING_YES, USE_OLAP) ** Illustrates high interaction coupling if all these parameters must be used as part of the runSql message Source: Bennett, McRobb, and Farmer, Object-Oriented Systems Analysis and Design (McGraw Hill, 2002), p. 352-3.
  • 41. Identity Coupling41  Refers to the level of connectivity of a design  If one object holds a reference / pointer to another object, that object knows the identity of the other, and therefore, exhibits identity coupling.  You can reduce identity coupling by :  eliminating unnecessary associations from your class diagram  by implementing associations in only one direction if bidirectional associations are unnecessary. Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 133.
  • 42. Identity Coupling42 This example has higher identity coupling. House has knows the identity of rooms (it has a room House Room collection) and room knows the identity of its house (it has a pointer to house). -m_rooms : Vector * -m_house : House 1 +addRoom() +setHouse() We may need this identity coupling (perhaps we +getRoom() also have a master list of Rooms that we need to examine independently of their house containers), Higher coupling But if we dont then we should eliminate bidirectional association. has House Room This example has less identity coupling. House knows the identity of rooms (it has a room -m_rooms : Vector * 1 collection) but room does not know the identity of +addRoom() its house. +getRoom() Lower coupling (preferred)
  • 43. Representational Coupling43  Classes should not depend on the specific representation / implementation details of another class.  e.g., accessing public attributes of a class results in a very high- degree of representational coupling.  Low representational coupling enables:  prototyping using frameworks and stubs  easier standardization (easier to standardize interfaces than implementations)  Extensibility  Representational coupling can be reduced by making attributes private, and using accessor and mutator methods (getters and setters) for those attributes.
  • 44. Representational Coupling44 Item +name : String Item abc = new Item(); +quantity : int abc.name = "towel"; High coupling abc.quantity = 3; Item -name : String -quantity : int +getName() : String +setName() : void Item abc = new Item(); Low coupling +getQuantity() : int abc.setName("towel"); (preferred) +setQuantity() : void Aabc.setQuantity(3);
  • 45. Subclass Coupling45  Inheritance is the strongest form of coupling!  When an object refers to a subclass object through a subclass reference, rather than through a more general superclass reference, you have subclass coupling.  A client should try to refer to the most general class possible, thereby decoupling the client from the specific subclasses. Client Superclass Client Superclass Subclass 1 Subclass 2 Subclass 1 Subclass 2 High coupling Low coupling (preferred) Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 134.
  • 46. Subclass Coupling46  Obviously you do need to create instances of subclasses.  Later,we will learn about the Factory pattern as a way to reduce subclass coupling.  As well, you should aim to structure your code so that only a small portion of the application deals with the subclass references (such as those to instantiate the subclasses), whereas the rest of the application deals only with general superclass types.
  • 47. Subclass Coupling47 House -m_rooms Room +addRoom() ControlHouse Kitchen Bedroom BoundaryHouse ControlRoomCreator ControlHouse ... public void newRoom(int roomType, ...) { ControlRoomCreator crc = new ControlRoomCreator(); Room r = crc.createRoom(roomType) ; m_house.addRoom( r ); }ControlRoomCreator House ... ... public Room createRoom(int roomType, ...) public void addRoom(Room r) { { if (roomType == Room.KITCHEN) m_rooms.addElement(r); return new Kitchen( ... ); } else if (roomType == Room.BEDROOM) return new Bedroom( ... ); }
  • 48. Coupling Review48  It is not high coupling per se that is so problematic, but high coupling to classes that are unstable (i.e., change frequently).  high coupling to stable and pervasive elements such as the standard Java libraries for string manipulation, collections, etc is not that problematic.  Thus, in particular, avoid high coupling for classes that change their interface or implementation frequently. Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 231
  • 49. Additional Class Design49 Guidelines  Mapping responsibilities using Information expert and creator  Avoid public fields  Prevent misuse by client  Establish invariants in constructor  Refactor duplicate code  Separate interface from implementation  Minimize interface size  Program to interface  Controllers  Replace Conditionals with Polymorphism  Improve Cohesion or Coupling by Pure Fabrication  Indirection  Don’t Talk to Strangers  Be Cautious with Inheritance  Favour object composition over class inheritance
  • 50. Design Guideline: Information50 Expert  Problem:  how to assign responsibilities to objects?  Solution:  Assign a responsibility to the class that has the information necessary to fulfill the responsibility.  Larman calls this the Information Expert principle Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 221-2
  • 51. Who is the Information Expert?51 Sale -m_date -m_time 1 contains * described by Sales Detail Product -quantity * -description 1 -price Who should have responsibility for calculating the grand total of the sale?
  • 52. Who is the Information Expert?52 getTotal() getSubTotal() : Sale : Sales Detail getPrice() : Product Now each object is responsible for providing the data it owns. Sale -m_date -m_time +getTotal() 1 contains * described by Sales Detail Product -quantity * -description 1 -price +getSubTotal() +getPrice()
  • 53. Multiple Information Experts53  The fulfillment of a responsibility often requires information that is spread across different classes of objects  Thusthere are often several partial information experts who will collaborate on the task of fulfilling the responsibility.
  • 54. Design Guideline: Creator54  Problem:  Who should be responsible for creating an object?  Solution:  Assign class B the responsibility to create an instance of class A if one or more of the following is true:  B aggregates A objects  B contains instances of A objects  B has the initializing data that will be passed to A when it is created.  B thus is the creator of A objects  Larman calls this the Creator principle Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 226
  • 55. Who is the Creator?55 Sale -m_date -m_time 1 contains * described by Sales Detail Product -quantity * -description 1 -price Q: Who should have responsibility for creating the Sales Detail objects? A: Since Sale aggregates Sales Detail, Sale should be the creator.
  • 56. Design Guideline: Avoid Public56 Fields  There should not be non-final public data members  Use properties/accessors and mutators (getters and setters) instead.  In languages that support properties (VB.NET, C#), use properties rather than getters and setters.  For boolean values, use naming convention IsAttr() instead of getAttr()
  • 57. Design Guideline: Prevent misuse by client57  A well designed class should not allow a class to be misused by its clients.  That is, mutators must ensure that data is being set correctly.  Parameters need to be checked for validity. private ArrayList _room; How can this class be misused? ... public Room getRoomByIndex(int index) { return (Room)_rooms.get(index); } private ArrayList _room; Solution #1 ... public Room getRoomByIndex(int index) { if (index >= 0 && index <= _rooms.size()) return (Room)_rooms.get(index); else return null; }
  • 58. Using Assertions58  For languages (Java 1.4, C#) that support them, to help catch future bugs, use assertions to detect violations at run-time.  An assertion is a boolean condition that must evaluate to true.  If the assertion is false, then an assertion exception is thrown.  Most environments allow you to turn assertion checking on or off. private ArrayList _room; Solution #2 ... public Room getRoomByIndex(int index) { assert index >= 0 && index <= _rooms.size(); if (index >= 0 && index <= _rooms.size()) return (Room)_rooms.get(index); else return null; }`
  • 59. Design Guideline: Establish invariants in constructor59  Invariants are data members that should not be modified in a class after they have been established/initialized.  If a class uses mutators (setters) to establish an invariant, then it is possible that future calls to the mutators will change the invariant.  Use a constructor to establish invariants.
  • 60. Design Guideline: Establish invariants in constructor60 public class Employee Using mutator to { establish invariant is private int _key; unreliable. public void setKey(int key){ _key = key; } } public class Employee Establish invariant { using constructor (java) private int _key; public Employee(int key){ _key = key; } public int getKey() { return _key; } } public class Employee Establish invariant { using constructor (C#) private int _key; public Employee(int key){ _key = key; } public int Key() { get { return _key; } }
  • 61. Design Guideline: Refactor Duplicate Code Segments61  Duplicate code segments are a maintenance nightmare.  Code needs to be refactored so that code segments occur only once.
  • 62. Design Guideline: Refactor Duplicate Code Segments62  Approaches:  Method invocation (duplication within single class)  Add a new method in same class that contains duplicate code  Inheritance (duplication within multiple classes)  Place duplicate code in a method in superclass.  Wont work if classes already have separate existing inheritance hierarchies.  Delegation (duplication within multiple classes)  Create separate class with public method that contains duplicate code.
  • 63. Design Guideline: Separate interface from implementation63  When the functionality in a class can be implemented in different ways, separate the interface from the implementation.
  • 64. Design Guideline: Separate interface from implementation64  That is, use an interface to describe the interface; use a class to describe the implementation.  This way, we could provide an alternate implementation without disrupting existing code. public class ArrayList implements List public interface List { { public int size() { return ... } public int size(); public boolean isEmpty() public boolean isEmpty(); { public void add(object item); ... public object get(int index); } ... ... } } public class Vector implements List { public int size() { return ... } public boolean isEmpty() { ... } ... }
  • 65. Design Guideline: Minimize Interface Size65  Try to design a class so that it provides the functionality you need but whose public interface is as small as possible.  Large numbers of methods and parameters often indicate high levels of coupling and complexity.  Use objects to encapsulate a long list of parameters to a method.
  • 66. Design Guideline: Minimize Interface66 Sizepublic Connection connectToDB(string driver, string connString, int accessRight, int ...){...} Too big! public Connection connectToDB(ConnectionInfo ci) { ... } Just right! public class ConnectionInfo { private string _driver; private string _connString; private int _accessRight; ... }
  • 67. Design Guideline: Program to67 interface  When an interface is available, program to it rather than to a particular concrete implementation.  Thisway, if in the future, a different implementation is used, fewer changes will be required.
  • 68. Design Guideline: Program to interface68 private ArrayList _room = new ArrayList(); ... public ArrayList getRooms() public interface List { { return _room; ... } } ... public class ArrayList implements List Programming to implementation – will require more changes { if we modify implementation in the future ... } private List _room = new ArrayList(); ... public class LinkedList implements List public List getRooms() { { ... return _room; } } ... Programming to interface – more adaptable if we decide to use different implementation in the future.
  • 69. Design Guideline: Replace Conditionals with Polymorphism69  Problem:  How to handle alternative responsibilities based on type (i.e., conditional variation using if-then-else or case statements) ?  Problem with using conditional variation is that if a new variation arises, it requires modification of the if-then-else structures, usually in several places. // constructor Room public Room(int roomType) { m_roomType = roomType m_roomType } getRoomType() public String getRoomType() { less ideal if (m_roomType == 1) return "Bedroom"; if (m_roomType == 2) return "Kitchen"; } Room abc = new Room(1); System.out.println( abc.getRoomType() ); Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 326
  • 70. Design Guideline: Replace Conditionals with Polymorphism70  Solution:  When related alternatives or behaviors vary by type (class), assign responsibility for the behavior, using polymorphism, to the types for which the behavior varies.  Thus, do not test for the type of an object and use conditional logic to perform varying alternatives based on type. public abstract String getRoomType(); Room ... public String getRoomType() { return "Bedroom"; getRoomType() } ... better public String getRoomType() { return "Kitchen"; Bedroom Kitchen } getRoomType() getRoomType() Kitchen abc = new Kitchen(); System.out.println( abc.getRoomType() ); Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 326
  • 71. Design Principle: Improve Cohesion or Coupling by Pure Fabrication71  Problem:  What object should have the responsibility, when the solution offered by the Information Expert (for example) principle violates High Cohesion or Low Coupling (or some other) principles?  Solution:  Assign a highly cohesive set of responsibilities to an artificial class with low coupling that does not represent a problem domain concept.  Such a class is a pure fabrication of the designers imagination: it does not relate to anything in the problem domain.  Larman calls this the Pure Fabrication principle. Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 329
  • 72. Pure Fabrication72  Suppose in our virtual street example, we wished to save our Houses, Rooms, Persons and Items that the user input in a database.  According to the information expert principle, who should be responsible for saving, for instance, the Rooms entered by the user?  According to the information expert principle, we should assign a responsibility to the class that has the information necessary to fulfill the responsibility.  Thus, according to the information expert principle, the Room class should be responsible for saving its information to a database, and the House class should be responsible for saving its information to a database, etc.
  • 73. Pure Fabrication73  To save the information to a database may very well require a large number of supporting database operations or methods, none related to the concept of Room-ness or House-ness.  Thus, each of our domain classes become much less cohesive.  As well, each of our domain classes will become coupled to the database interface (e.g., Java JDBC or Microsoft ADO).  Thus, each of our domain classes become highly coupled to something external.  To solve the problem, we need to make up (that is, to fabricate) a new class that will handle the database tasks. House Room Item PersistantStorage Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 329
  • 74. Design Principle: Indirection74  Problem:  How to assign responsibility so as to avoid direct coupling between two or more things.  How to de-couple objects so that low coupling is supported and reuse potential is high?  Solution:  Assign the responsibility to an intermediate object to mediate between other components so that they are not directly coupled.  The intermediary creates an indirection between the other components.  Larman calls this the Indirection principle. Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 332
  • 75. Indirection75  In our last example, the PersistantStorage fabrication acts as an intermediary between the domain objects and the database.  Many of the other patterns we will look at are specializations of indirection.  "Most problems in computer science can be solved by another level of indirection."  however, "Most problems in performance can be solved by removing another layer of indirection" ! Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 333
  • 76. Design Principle: Dont Talk to Strangers76  Problem:  How to design classes that are protected from changes in other classs interfaces?  That is, if an object has knowledge of the internal structure of other objects, then it suffers from high coupling. How can an object use a service from an indirect object without being coupled to the internal structure of that object.  Solution:  Dont rely on another classs knowledge of other objects.  Instead, assign the responsibility to a clients direct object to collaborate with an indirect object.  Larman calls this the Dont Talk to Strangers principle. Source: Craig Larman, Applying UML and Patterns , 1st Edition (Prentice Hall, 1998), p. 400
  • 77. Dont Talk to Strangers // Returns the total number of holdings for the client77 public int getNumHoldings(Client c) { int num = 0; HoldingController for (int i=0; i<size(); i++) { m_holdings: Vector Holding holding = m_holdings.get(i); getNumHoldings(): int if ( c.getID() == holding.getClient().getID() ) num++; } Holding return num; } m_stock: Stock m_client: Client Message being sent to getClient(): Client getStock(): Stock familiar object (Holding) stranger object (Client) Client Stockm_id: int m_symbol: Stringm_name: String m_value: doublegetID(): int getSymbol(): StringgetName(): String getValue: double itemName = house.getRoom(0).getItem(0).getName(); familiar object (house) stranger object (room) stranger object (item)
  • 78. Dont Talk to Strangers78  Observe the following constraints on what objects you should send messages to within a method:  the this object  a parameter of the method  an attribute of this  an element of a collection which is an attribute of this  an object created within the method  The intent of these constraints is to avoid coupling a client to knowledge of indirect objects and the object connections between objects. Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 336
  • 79. If not to strangers, then who?79  Following these constraints requires adding new public operations to the "familiars" of an object. // Returns the total number of holdings for the client public int getNumHoldings(Client c) { int num = 0; for (int i=0; i<size(); i++) { Holding holding = m_holdings.get(i); if ( c.getID() == holding.getClientID() ) num++; } return num; }  Of course, this may not seem worth the bother. Certainly, try to avoid talking to a stranger of a stranger (e.g., second example on last slide).
  • 80. Design Principle: Be Cautious with Inheritance80  Inheritance is a powerful way to use polymorphism and reduce code duplication.  However, some potential problems with inheritance are  It is the strongest form of coupling  Encapsulation is weak within an generalization hierarchy (changes in superclass ripple down to modify the subclasses).  Inheritance relationships are fixed at run-time.  Sometimes aggregation is a better choice than an ill- thought out inheritance hierarchy.
  • 81. Example of Inheritance Problem81 Employee This looks okay, but it contains a semantic error. Can you see it? Manager Programmer Employee «instance» Hint: What happens if we want to change Manager Programmer Randy : Programmer Randy’s class to Manager at run-time? Answer: is an employee just their job, or is a job a role that an employee has? That is, an employee has a job. A job is a role that an employee has, it is not a “kind of” employee. “Has a” indicates an aggregation relationship. has a Employee Job 1 * Manager Programmer Now we can promote an employee simply by changing its job link at run-time. Source: Arlow and Neustadt, UML and the Unified Process (Addison-Wesley, 2002), p. 265-6.
  • 82. Design Principle: Delegation over class inheritance82  One way to deal with the problem of inheritance (weak encapsulation of subclasses) is to favour object composition and delegation over class inheritance if code reuse is your only goal in using inheritance.  Use inheritance if there is a strong is a relationship; otherwise, look at using object composition instead. Rectangle Rectangle -width -height -width -height +calculateArea() +calculateArea() Window 1 +open() Window +close() public int calculateArea() -m_rect : Rectangle { Is there a strong “is a” relationship +open() return m_rect.calculateArea(); +close() between Rectangle and Window? +calculateArea() } What happens when a new attribute, This uses object delegation instead to handle the such as fill color, is added to Rectangle? calculateArea request; it is somewhat analogous to Window will then inherit a characteristic letting the superclass handle the request, except here which a Window does not have. the request is delegated to another object it contains.
  • 83. What Next?83  At this point, you should have detailed interaction diagrams along with a detailed class diagram in which responsibilities have been mapped to class methods.  Depending upon the software process being used, the next step might be:  implement the classes defined in the class diagram and test. Then refine the classes using design patterns as separate iteration.  refine the classes in a second iteration through the design phase using design patterns, then implement and test.
  • 84. Mapping Design to Code84  Your class diagram shows which methods and attributes need to be implemented.  That is, by just looking at your class diagram, you can create the attributes and the method stubs.  Your interaction diagrams show the messages that are sent between objects in response to a method invocation.  That is, they show how a given method or methods will be implemented.  The sequence of these messages translates to a series of statements in a method definition.
  • 85. Order of Implementation85  Classes need to be implemented (and ideally, fully tested) from least-coupled to most-coupled.  This will typically mean that you will implement your basic domain classes first. Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 311
  • 86. Test-First Programming86  On of the precepts of Extreme Programming (XP) method is test-first programming, in which class testing code is written before the code to be tested.  This ensures that testing gets done, but it also helps clarify the design of the interfaces of a class.  This also creates a library of unit tests, which helps to verify correctness of a system. Source: Craig Larman, Applying UML and Patterns , 2nd Edition (Prentice Hall, 2001), p. 311