OO Development 6 - Design

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    1 Favorite

    OO Development 6 - Design - Presentation Transcript

    1. DESIGN Design ... is a recognition of the relation between various things … You can’t invent a design. You recognise it, in the fourth dimension. That is, with your blood and your bones, as well as with your eyes. D. H. Lawrence, “Art and Morality” (1936 )
    2. Our Process
      • Reminder of object-oriented development process we are following in this course is that there are four phases :
        • Inception
        • Elaboration
        • Construction
        • Transition
      • Each phase consists of one or more iterations of the following workflows :
        • Requirements
        • Analysis & Design
        • Implementation
        • Test
      • In this section, we are going to examine the design workflow principally in the context of the Elaboration and construction phases.
      Inception Elaboration Construction Transition 1 2 3 4 5 6 7 8 Requirements Analysis Design Implementation Test
    3. Design Workflow
      • 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.
    4. Object-Oriented Design
      • 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.
    5. Analysis versus Design
      • The boundary between analysis and design can be quite vague; they often overlap.
      • Some software processes merge the analysis and design stages.
        • In real 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.
    6. System Design and Detailed 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.
    7. What is Software Architecture?
      • The system design of an application is also referred to as software architecture .
      • Software architecture is a shared understanding of a system's 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.
    8. System Design
      • 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.
    9. Layering
      • 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.
    10. Layering
      • 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 layer's 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.
    11. Layering
      • 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.
      Source: Eric Evans, Domain-Driven Design (Addison-Wesley, 2003), p. 69. Layer 1 Layer 2 Layer 3 Layer 4
    12. Open versus Closed Architecture
      • 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.
    13. Open versus Closed Architecture
      • 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 1 Layer 2 Layer 3 Layer 4 Layer 1 Layer 2 Layer 3 Layer 4 Arrows indicate message flow Source: Bennett, McRobb, and Farmer, Object-Oriented Systems Analysis and Design (McGraw Hill, 2002), p. 326. Closed layer architecture Open layer architecture
    14. Common Layer Architectures Presentation Source: Bennett, McRobb, and Farmer, Object-Oriented Systems Analysis and Design (McGraw Hill, 2002), p. 328-30. Business Logic Three layer architecture Data Access Presentation Application Four layer architecture Domain Data Access View Controller MVC architecture Model Boundary Control BCE architecture Entity
    15. Common Layer Architectures I
      • Presentation Layer
        • Responsible for showing information to the user and interpreting the user's 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.
      Data Access Business Presentation
    16. Common Layer Architectures II
      • Boundary
        • Boundary layer refer to any classes that interact directly with the actors.
        • Should only communicate with Control layer classes
      • Entity
        • Entity layer contain classes that represent objects in the problem domain.
        • Should have no knowledge of Boundary or Control classes.
      • Control
        • Control layer classes coordinate between the boundary and entity layers.
        • Represent the application logic
        • Often, each use case will have a control class
      Entity Control Boundary ViewCustomerList Customer «entity» Customer «control» CustomerListController «boundary» ViewCustomerList CustomerListController
    17. Common Layer Architectures III
      • Presentation Layer
        • Responsible for showing information to the user and interpreting the user's commands.
      • Application Layer
        • Defines the job the software is supposed to do and directs the domain objects.
      • Domain Layer
        • 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. Infrastructure Domain Application Presentation
    18. Common Layer Architectures IV
      • Presentation Layer
        • Responsible for showing information to the user and interpreting the user's commands.
      • Presentation Helper Layer
        • This layer hides all the complexity of the application layer and it is adapted to the specific presentation layer implementation .
      • Service Layer
        • The service layer provides a layer of services to 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 Persistence Domain Service Presentation Helper Presentation
    19. Common Layer Architectures V
      • UI Component Layer
        • Responsible for showing information to the user and interpreting the user's commands using UI components (windows forms, web pages, user controls, etc)
      • UI Process Layer
        • Handles validation and navigation between UI components.
      • Business Process Layer
        • Business processes reflect the macro-level activities that the business 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 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 Data Access Helper Business Process UI Process UI Component Domain Data Access Components Infrastructure
    20. Diagramming Layers
    21. Class Design
      • 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.
      Analysis class Design class
    22. Class Design
      • 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
    23. Class Design
      • 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.
    24. Symptoms of Poor Design
      • 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.
    25. Class Design Principles
      • Completeness and Sufficiency
      • Primitiveness
      • High Cohesion
      • Low Coupling
    26. Completeness and Sufficiency
      • 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.
    27. Primitiveness
      • 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.
      Source: Arlow and Neustadt, UML and the Unified Process (Addison-Wesley, 2002), p. 262. Yes! No!
    28. High Cohesion
      • Cohesion is a measure of the diversity of an class's 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.
    29. Cohesion
      • 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
      Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 129. low cohesion How many abstractions does this class contain? low cohesion How many abstractions does this class contain?
    30. Cohesion
      • 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.
        • Similar to rule against transitive dependencies in database normalization.
        • You may have to specialize the class along different dimensions based on the different abstractions.
      Separate the two abstractions Account Customer 1..* 1
    31. Low Cohesion and Inheritance Problems when we further specialize the classes How many abstractions does each subclass contain?
    32. High Cohesion and Inheritance Separate the two abstractions Then specialize the two abstractions
    33. Low Coupling
      • 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.
    34. Coupling Menu is coupled to two other classes Now Menu is coupled to just one class
    35. Coupling Example lower coupling higher coupling
    36. Coupling
      • 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.
    37. Stair vs Finger in Sequence Diagrams Finger Stair Indicative of high coupling Indicative of low coupling
    38. Types of Coupling
      • 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.
    39. Interaction Coupling
      • 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.
      Source: Bennett, McRobb, and Farmer, Object-Oriented Systems Analysis and Design (McGraw Hill, 2002), p. 352-3. MyDataAccess da = new MyDataAccess(); da.setName( " wine"); da.setExtension("mdb"); da.setType("Microsoft Access"); da.setDriverAccess("odbc"); 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 messages must be sent before runSql message ** Illustrates high interaction coupling if all these parameters must be used as part of the runSql message
    40. Identity Coupling
      • 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.
    41. Identity Coupling This example has higher identity coupling. House knows the identity of rooms (it has a room collection) and room knows the identity of its house (it has a pointer to house). We may need this identity coupling (perhaps we also have a master list of Rooms that we need to examine independently of their house containers), But if we don't then we should eliminate bidirectional association. This example has less identity coupling. House knows the identity of rooms (it has a room collection) but room does not know the identity of its house. Higher coupling Lower coupling (preferred)
    42. Representational Coupling
      • 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.
    43. Representational Coupling Item abc = new Item(); abc.name = "towel"; abc.quantity = 3; Item abc = new Item(); abc.setName("towel"); Aabc.setQuantity(3); High coupling Low coupling (preferred)
    44. Subclass Coupling
      • 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.
      Source: Charles Richter, Designing Flexible Object-Oriented Systems with UML (Macmillan, 1999), p. 134. High coupling Low coupling (preferred)
    45. Subclass Coupling
      • 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.
    46. Subclass Coupling ... public void addRoom(Room r) { m_rooms.addElement(r); } ... public Room createRoom(int roomType, ...) { if (roomType == Room.KITCHEN) return new Kitchen( ... ); else if (roomType == Room.BEDROOM) return new Bedroom( ... ); } House ControlRoomCreator ... public void newRoom(int roomType, ...) { ControlRoomCreator crc = new ControlRoomCreator(); Room r = crc.createRoom(roomType) ; m_house.addRoom( r ); } ControlHouse
    47. Coupling Review
      • 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 , 2 nd Edition (Prentice Hall, 2001), p. 231
    48. Additional Class Design 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
    49. Design Guideline: Information 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 , 2 nd Edition (Prentice Hall, 2001), p. 221-2
    50. Who is the Information Expert? Who should have responsibility for calculating the grand total of the sale?
    51. Who is the Information Expert? Now each object is responsible for providing the data it owns.
    52. Multiple Information Experts
      • The fulfillment of a responsibility often requires information that is spread across different classes of objects
        • Thus there are often several partial information experts who will collaborate on the task of fulfilling the responsibility.
    53. Design Guideline: Creator
      • 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 , 2 nd Edition (Prentice Hall, 2001), p. 226
    54. Who is the Creator? Q: Who should have responsibility for creating the Sales Detail objects? A: Since Sale aggregates Sales Detail, Sale should be the creator.
    55. Design Guideline: Avoid Public 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 Is Attr() instead of getAttr()
    56. Design Guideline: Prevent misuse by client
      • 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; ... public Room getRoomByIndex(int index) { return (Room)_rooms.get(index); } private ArrayList _room; ... public Room getRoomByIndex(int index) { if (index >= 0 && index <= _rooms.size()) return (Room)_rooms.get(index); else return null; } How can this class be misused? Solution #1
    57. Using Assertions
      • 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; ... 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; }` Solution #2
    58. Design Guideline: Establish invariants in constructor
      • 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.
    59. Design Guideline: Establish invariants in constructor public class Employee { private int _key; public void setKey(int key){ _key = key; } } public class Employee { private int _key; public Employee(int key){ _key = key; } public int getKey() { return _key; } } Establish invariant using constructor (java) Using mutator to establish invariant is unreliable. public class Employee { private int _key; public Employee(int key){ _key = key; } public int Key() { get { return _key; } } Establish invariant using constructor (C#)
    60. Design Guideline: Refactor Duplicate Code Segments
      • Duplicate code segments are a maintenance nightmare.
        • Code needs to be refactored so that code segments occur only once.
    61. Design Guideline: Refactor Duplicate Code Segments
      • 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.
          • Won't work if classes already have separate existing inheritance hierarchies.
        • Delegation (duplication within multiple classes)
          • Create separate class with public method that contains duplicate code.
    62. Design Guideline: Separate interface from implementation
      • When the functionality in a class can be implemented in different ways, separate the interface from the implementation.
    63. Design Guideline: Separate interface from implementation
      • 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 interface List { public int size(); public boolean isEmpty(); public void add(object item); public object get(int index); ... } public class ArrayList implements List { public int size() { return ... } public boolean isEmpty() { ... } ... } public class Vector implements List { public int size() { return ... } public boolean isEmpty() { ... } ... }
    64. Design Guideline: Minimize Interface Size
      • 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.
    65. Design Guideline: Minimize Interface Size public Connection connectToDB(string driver, string connString, int accessRight, int ...) { ... } public Connection connectToDB(ConnectionInfo ci) { ... } public class ConnectionInfo { private string _driver; private string _connString; private int _accessRight; ... } Just right! Too big!
    66. Design Guideline: Program to interface
      • When an interface is available, program to it rather than to a particular concrete implementation.
        • This way, if in the future, a different implementation is used, fewer changes will be required.
    67. Design Guideline: Program to interface private ArrayList _room = new ArrayList(); ... public ArrayList getRooms() { return _room; } ... public interface List { ... } public class ArrayList implements List { ... } public class LinkedList implements List { ... } private List _room = new ArrayList(); ... public List getRooms() { return _room; } ... Programming to implementation – will require more changes if we modify implementation in the future Programming to interface – more adaptable if we decide to use different implementation in the future.
    68. Design Guideline: Replace Conditionals with Polymorphism
      • 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.
      Source: Craig Larman, Applying UML and Patterns , 2 nd Edition (Prentice Hall, 2001), p. 326 // constructor public Room(int roomType) { m_roomType = roomType } public String getRoomType() { if (m_roomType == 1) return &quot;Bedroom&quot;; if (m_roomType == 2) return &quot;Kitchen&quot;; } Room abc = new Room(1); System.out.println( abc.getRoomType() ); less ideal
    69. Design Guideline: Replace Conditionals with Polymorphism
      • 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.
      Source: Craig Larman, Applying UML and Patterns , 2 nd Edition (Prentice Hall, 2001), p. 326 ... public String getRoomType() { return &quot;Bedroom&quot;; } ... public String getRoomType() { return &quot;Kitchen&quot;; } public abstract String getRoomType(); Kitchen abc = new Kitchen(); System.out.println( abc.getRoomType() ); better
    70. Design Principle: Improve Cohesion or Coupling by Pure Fabrication
      • 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 designer's 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 , 2 nd Edition (Prentice Hall, 2001), p. 329
    71. Pure Fabrication
      • 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.
    72. Pure Fabrication
      • 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.
      Source: Craig Larman, Applying UML and Patterns , 2 nd Edition (Prentice Hall, 2001), p. 329
    73. Design Principle: Indirection
      • 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 , 2 nd Edition (Prentice Hall, 2001), p. 332
    74. Indirection
      • 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.
      • &quot;Most problems in computer science can be solved by another level of indirection.&quot;
        • however, &quot;Most problems in performance can be solved by removing another layer of indirection&quot; !
      Source: Craig Larman, Applying UML and Patterns , 2 nd Edition (Prentice Hall, 2001), p. 333
    75. Design Principle: Don't Talk to Strangers
      • Problem:
        • How to design classes that are protected from changes in other class's 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:
        • Don't rely on another class's knowledge of other objects.
        • Instead, assign the responsibility to a client's direct object to collaborate with an indirect object.
      • Larman calls this the Don't Talk to Strangers principle.
      Source: Craig Larman, Applying UML and Patterns , 1 st Edition (Prentice Hall, 1998), p. 400
    76. Don't Talk to Strangers // 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.getClient().getID() ) num++; } return num; } familiar object (Holding) stranger object (Client) itemName = house.getRoom(0).getItem(0).getName(); familiar object (house) Message being sent to stranger object (room) stranger object (item)
    77. Don't Talk to Strangers
      • 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 , 2 nd Edition (Prentice Hall, 2001), p. 336
    78. If not to strangers, then who?
      • Following these constraints requires adding new public operations to the &quot;familiars&quot; of an object.
      • 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).
      // 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; }
    79. Design Principle: Be Cautious with Inheritance
      • 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.
    80. Example of Inheritance Problem This looks okay, but it contains a semantic error. Can you see it? Hint: What happens if we want to change 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. Source: Arlow and Neustadt, UML and the Unified Process (Addison-Wesley, 2002), p. 265-6. Now we can promote an employee simply by changing its job link at run-time.
    81. Design Principle: Delegation over class inheritance
      • 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.
      Is there a strong “is a” relationship between Rectangle and Window? What happens when a new attribute, such as fill color, is added to Rectangle? Window will then inherit a characteristic which a Window does not have. This uses object delegation instead to handle the calculateArea request; it is somewhat analogous to letting the superclass handle the request, except here the request is delegated to another object it contains. public int calculateArea() { return m_rect.calculateArea(); }
    82. What Next?
      • 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.
    83. Mapping Design to Code
      • 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.
    84. Order of Implementation
      • 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 , 2 nd Edition (Prentice Hall, 2001), p. 311
    85. Test-First Programming
      • 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 , 2 nd Edition (Prentice Hall, 2001), p. 311

    + randyconnollyrandyconnolly, 6 months ago

    custom

    306 views, 1 favs, 0 embeds more stats

    Course material from my Object-Oriented Development more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 306
      • 306 on SlideShare
      • 0 from embeds
    • Comments 0
    • Favorites 1
    • Downloads 0
    Most viewed embeds

    more

    All embeds

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories

    Tags