Object Oriented Design


Published on

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Object Oriented Design

    1. 1. Object Oriented Design Sudarsun S., M.Tech Director – R & D Checktronix India Pvt Ltd Chennai 600010
    2. 2. Objectives <ul><li>To explain how a software design may be represented as a set of interacting objects that manage their own state and operations </li></ul><ul><li>To introduce various models that describe an object-oriented design </li></ul><ul><li>To introduce design patterns </li></ul>
    3. 3. What is an OBJECT <ul><li>An instance of a CLASS </li></ul><ul><li>Contains meaningful data </li></ul><ul><li>Concepts that occupy memory space at runtime are, according to the definition, objects </li></ul><ul><ul><li>If not, they are CLASSES </li></ul></ul><ul><ul><li>For example: data type vs. double </li></ul></ul>
    4. 4. A little Quiz… <ul><li>#1 Class or Object? </li></ul>Dog is a generalization of Scooby-Doo Dog Scooby-Doo
    5. 5. A little Quiz (cont’d)… <ul><li>#2 Class or Object? </li></ul>The concept of subclass ! Dog is a subclass of the Animal class Animal is a generalization of Dog Dog Scooby-Doo Animal
    6. 6. A little Quiz (cont’d)… <ul><li>#3 Class or Object? </li></ul>The concept of polymorphism ! Animal Dog Bird
    7. 7. Characteristics of OOD <ul><li>Objects are abstractions of real-world or system entities and manage themselves </li></ul><ul><li>Objects are independent and encapsulate state and representation information. </li></ul><ul><li>System functionality is expressed in terms of object services </li></ul><ul><li>Shared data areas are eliminated </li></ul><ul><ul><li>Objects communicate by message passing </li></ul></ul><ul><li>Objects may be distributed </li></ul><ul><li>Objects may execute sequentially or in parallel </li></ul>
    8. 8. Interacting objects
    9. 9. Advantages of OOD <ul><li>Easier maintenance. Objects may be understood as stand-alone entities </li></ul><ul><li>Objects are appropriate reusable components </li></ul><ul><li>For some systems, there may be an obvious mapping from real world entities to system objects </li></ul>
    10. 10. Object-oriented development <ul><li>Object-oriented analysis, design and programming are related but distinct </li></ul><ul><li>OOA is concerned with developing an object model of the application domain </li></ul><ul><li>OOD is concerned with developing an object-oriented system model to implement requirements </li></ul><ul><li>OOP is concerned with realising an OOD using an OO programming language such as Java or C++ </li></ul>
    11. 11. Objects and object classes <ul><li>Objects are entities in a software system which represent instances of real-world and system entities </li></ul><ul><li>Object classes are templates for objects </li></ul><ul><ul><li>Classes may be used to create objects </li></ul></ul><ul><li>Object classes may inherit attributes and services from other object classes </li></ul>
    12. 12. Object communication <ul><li>Conceptually, objects communicate by message passing </li></ul><ul><li>Messages </li></ul><ul><ul><li>The name of the service requested by the calling object. </li></ul></ul><ul><ul><li>Copies of the information required to execute the service and the name of a holder for the result of the service. </li></ul></ul><ul><li>In practice, messages are often implemented by procedure (a.k.a. method) calls </li></ul><ul><ul><li>Name = method name </li></ul></ul><ul><ul><li>Information = parameter list </li></ul></ul><ul><ul><li>Result holder = method return value </li></ul></ul>
    13. 13. Message examples <ul><li>// Call a method associated with a buffer // object that returns the next value // in the buffer </li></ul><ul><li>v = circularBuffer.Get() ; </li></ul><ul><li>// Call the method associated with a // thermostat object that sets the // temperature to be maintained </li></ul><ul><li>thermostat.setTemp(20) ; </li></ul>
    14. 14. Generalisation and inheritance <ul><li>Objects are members of classes which define attribute types and operations </li></ul><ul><li>Classes may be arranged in a class hierarchy where one class (a super-class) is a generalisation of one or more other classes (sub-classes) </li></ul><ul><li>A sub-class inherits the attributes and operations from its super class and may add new methods or attributes of its own </li></ul><ul><li>It is a reuse mechanism at both the design and the programming level </li></ul><ul><li>Inheritance introduces complexity and this is undesirable, especially in critical systems </li></ul>
    15. 15. A generalisation hierarchy
    16. 16. Object Relationships <ul><li>Objects and object classes participate in relationships with other objects and object classes </li></ul><ul><ul><li>In UML, such a relationship is indicated by an association </li></ul></ul><ul><li>Associations may be annotated with information that describes the association </li></ul>
    17. 17. Object identification <ul><li>Identifying objects (or object classes) is the most difficult part of object oriented design </li></ul><ul><li>There is no “magic formula” for object identification </li></ul><ul><ul><li>It relies on the skill, experience and domain knowledge of system designers </li></ul></ul><ul><li>Object identification is an iterative process </li></ul><ul><ul><li>You are unlikely to get it right first time </li></ul></ul>
    18. 18. Approaches to identification <ul><li>Use a grammatical approach based on a natural language description of the system (used in HOOD method) </li></ul><ul><li>Base the identification on tangible things in the application domain </li></ul><ul><li>Use a behavioural approach and identify objects based on what participates in what behaviour </li></ul><ul><li>Use a scenario-based analysis – the objects, attributes and methods in each scenario are identified </li></ul>
    19. 19. Object interface specification <ul><li>Object interfaces have to be specified so that the objects and other components can be designed in parallel </li></ul><ul><li>Designers should avoid designing the interface representation but should hide this in the object itself </li></ul><ul><li>Objects may have several interfaces which are viewpoints on the methods provided </li></ul>
    20. 20. Examples of design models <ul><li>Sub-system models that show logical groupings of objects into coherent subsystems </li></ul><ul><ul><li>UML package diagrams </li></ul></ul><ul><li>Sequence models that show the sequence of object interactions </li></ul><ul><ul><li>UML sequence diagrams </li></ul></ul><ul><li>State machine models that show how individual objects change their state in response to events </li></ul><ul><ul><li>UML statechart diagrams </li></ul></ul><ul><li>Other models include use-case models, aggregation models, generalisation models,etc. </li></ul>
    21. 21. Weather station subsystems
    22. 22. Weather station - data collection sequence
    23. 23. State charts <ul><li>Object states </li></ul><ul><li>State transitions triggered by requests to objects </li></ul>
    24. 24. OO Design Process – Access Layer <ul><li>Create Mirror classes: For every business class identified and created, create one access class. </li></ul><ul><li>Simplify classes and their relationships – to eliminate redundant classes and structures </li></ul><ul><li>Redundant classes: Do not keep 2 classes that perform similar request and results translation activities. Select one and eliminate the other. </li></ul><ul><li>Methods: Revisit the classes that consist of only one or two methods to see if they can be eliminated or combined with existing classes. </li></ul>
    25. 25. Object Oriented Design Process <ul><li>Design the view layer classes </li></ul><ul><ul><li>Design the macro & micro level user interface, identifying view layer objects </li></ul></ul><ul><ul><li>Test usability and user satisfaction </li></ul></ul><ul><li>From the UML class diagram, begin to extrapolate the classes to build and classes to reuse. </li></ul><ul><li>Also think about the inheritance structure. </li></ul><ul><li>If we have several classes that seem related but have specific differences, probably it means an inheritance structure. </li></ul><ul><li>All designed components must trace back to the user requirements. </li></ul>
    26. 26. Example: Invoice
    27. 27. Example: Invoice <ul><li>Classes that come to mind: Invoice , LineItem , and Customer </li></ul><ul><li>Good idea to keep a list of candidate classes </li></ul><ul><li>Brainstorm, simply put all ideas for classes onto the list </li></ul><ul><li>You can cross not useful ones later </li></ul>
    28. 28. Finding Classes <ul><li>Keep the following points in mind: </li></ul><ul><ul><li>Class represents set of objects with the same behavior </li></ul></ul><ul><ul><ul><li>Entities with multiple occurrences in problem description are good candidates for objects </li></ul></ul></ul><ul><ul><ul><li>Find out what they have in common </li></ul></ul></ul><ul><ul><ul><li>Design classes to capture commonalities </li></ul></ul></ul><ul><ul><li>Represent some entities as objects, others as primitive types </li></ul></ul><ul><ul><ul><li>Should we make a class Address or use a String? </li></ul></ul></ul><ul><ul><li>Not all classes can be discovered in analysis phase </li></ul></ul><ul><ul><li>Some classes may already exist </li></ul></ul>
    29. 29. CRC Card <ul><li>CRC Card </li></ul><ul><li>Describes a class, its responsibilities, and its collaborators </li></ul><ul><li>Use an index card for each class </li></ul><ul><li>Pick the class that should be responsible for each method (verb) </li></ul><ul><li>Write the responsibility onto the class card </li></ul><ul><li>Indicate what other classes are needed to fulfill responsibility (collaborators) </li></ul>
    30. 30. CRC Card
    31. 31. Self Check <ul><li>Suppose the invoice is to be saved to a file. Name a likely collaborator. </li></ul><ul><li>Looking at the invoice, what is a likely responsibility of the Customer class? </li></ul><ul><li>What do you do if a CRC card has ten responsibilities? </li></ul>
    32. 32. Answers <ul><li>FileWriter </li></ul><ul><li>To produce the shipping address of the customer. </li></ul><ul><li>Reword the responsibilities so that they are at a higher level, or come up with more classes to handle the responsibilities. </li></ul>
    33. 33. Relationships Between Classes <ul><li>Inheritance </li></ul><ul><li>Aggregation </li></ul><ul><li>Dependency </li></ul>
    34. 34. Inheritance <ul><li>Is-a relationship </li></ul><ul><li>Relationship between a more general class (superclass) and a more specialized class (subclass) </li></ul><ul><li>Every savings account is a bank account </li></ul>Continued…
    35. 35. Inheritance <ul><li>Every circle is an ellipse (with equal width and height) </li></ul><ul><li>It is sometimes abused </li></ul><ul><ul><li>Should the class Tire be a subclass of a class Circle ? </li></ul></ul><ul><ul><ul><ul><li>The has-a relationship would be more appropriate </li></ul></ul></ul></ul>
    36. 36. Aggregation <ul><li>Has-a relationship </li></ul><ul><li>Objects of one class contain references to objects of another class </li></ul><ul><li>Use an instance variable </li></ul><ul><ul><li>A tire has a circle as its boundary: </li></ul></ul><ul><li>Every car has a tire (in fact, it has four) </li></ul>class Tire { . . . private String rating; private Circle boundary; }
    37. 37. Example class Car extends Vehicle { . . . private Tire[] tires; }
    38. 38. Example UML Notation for Inheritance and Aggregation
    39. 39. Dependency <ul><li>Uses relationship </li></ul><ul><li>Example: many of our applications depend on the Scanner class to read input </li></ul><ul><li>Aggregation is a stronger form of dependency </li></ul><ul><li>Use aggregation to remember another object between method calls </li></ul>
    40. 40. UML Relationship Symbols Open Dotted Dependency Diamond Solid Aggregation Triangle Dotted Interface Implementation Triangle Solid Inheritance Arrow Tip Line Style Symbol Relationship
    41. 41. Self Check <ul><li>Consider the Bank and BankAccount classes. How are they related? </li></ul><ul><li>Consider the BankAccount and SavingsAccount objects. How are they related? </li></ul><ul><li>Consider the BankAccountTester class. Which classes does it depend on? </li></ul>
    42. 42. Answers <ul><li>Through aggregation. The bank manages bank account objects. </li></ul><ul><li>Through inheritance. </li></ul><ul><li>The BankAccount , System , and PrintStream classes. </li></ul>
    43. 43. Attributes and Methods in UML Attributes and Methods in a Class Diagram
    44. 44. Multiplicities <ul><li>any number (zero or more): * </li></ul><ul><li>one or more: 1..* </li></ul><ul><li>zero or one: 0..1 </li></ul><ul><li>exactly one: 1 </li></ul>An Aggregation Relationship with Multiplicities
    45. 45. Aggregation and Association <ul><li>Association: more general relationship between classes </li></ul><ul><li>Use early in the design phase </li></ul><ul><li>A class is associated with another if you can navigate from objects of one class to objects of the other </li></ul><ul><li>Given a Bank object, you can navigate to Customer objects </li></ul>Continued…
    46. 46. Aggregation and Association An Association Relationship
    47. 47. Five-Part Development Process <ul><li>Gather requirements </li></ul><ul><li>Use CRC cards to find classes, responsibilities, and collaborators </li></ul><ul><li>Use UML diagrams to record class relationships </li></ul><ul><li>Use javadoc to document method behavior </li></ul><ul><li>Implement your program </li></ul>
    48. 48. Printing an Invoice – Requirements <ul><li>Task: print out an invoice </li></ul><ul><li>Invoice: describes the charges for a set of products in certain quantities </li></ul><ul><li>Omit complexities </li></ul><ul><ul><li>Dates, taxes, and invoice and customer numbers </li></ul></ul><ul><li>Print invoice </li></ul><ul><ul><li>Billing address, all line items, amount due </li></ul></ul><ul><li>Line item </li></ul><ul><ul><li>Description, unit price, quantity ordered, total price </li></ul></ul><ul><li>For simplicity, do not provide a user interface </li></ul><ul><li>Test program: adds line items to the invoice and then prints it </li></ul>Continued…
    49. 49. Sample Invoice
    50. 50. CRC Cards <ul><li>Discover classes </li></ul><ul><li>Nouns are possible classes </li></ul>Invoice Address LineItem Product Description Price Quantity Total Amount Due
    51. 51. CRC Cards <ul><li>Analyze classes </li></ul>Invoice Address LineItem // Records the product and the quantity Product Description // Field of the Product class Price // Field of the Product class Quantity // Not an attribute of a Product Total // Computed–not stored anywhere Amount Due // Computed–not stored anywhere Continued…
    52. 52. CRC Cards <ul><li>Classes after a process of elimination </li></ul>Invoice Address LineItem Product
    53. 53. CRC Cards for Printing Invoice <ul><li>Invoice and Address must be able to format themselves: </li></ul>
    54. 54. CRC Cards for Printing Invoice <ul><li>Add collaborators to invoice card: </li></ul>
    55. 55. CRC Cards for Printing Invoice <ul><li>Product and LineItem CRC cards: </li></ul>
    56. 56. CRC Cards for Printing Invoice <ul><li>Invoice must be populated with products and quantities: </li></ul>
    57. 57. Printing an Invoice – UML Diagrams The Relationships Between the Invoice Classes
    58. 58. Method Documentation <ul><li>Use javadoc documentation to record the behavior of the classes </li></ul><ul><li>Leave the body of the methods blank </li></ul><ul><li>Run javadoc to obtain formatted version of documentation in HTML format </li></ul><ul><li>Advantages: </li></ul><ul><ul><li>Share HTML documentation with other team members </li></ul></ul><ul><ul><li>Format is immediately useful: Java source files </li></ul></ul><ul><ul><li>Supply the comments of the key methods </li></ul></ul>
    59. 59. Method Documentation – Invoice class /** Describes an invoice for a set of purchased products. */ public class Invoice { /** Adds a charge for a product to this invoice. @param aProduct the product that the customer ordered @param quantity the quantity of the product */ public void add(Product aProduct, int quantity) { } /** Formats the invoice. @return the formatted invoice */ public String format() { } }
    60. 60. Method Documentation – LineItem class /** Describes a quantity of an article to purchase and its price. */ public class LineItem { /** Computes the total cost of this line item. @return the total price */ public double getTotalPrice() { } /** Formats this item. @return a formatted string of this line item */ public String format() { } }
    61. 61. Method Documentation – Product class /** Describes a product with a description and a price. */ public class Product { /** Gets the product description. @return the description */ public String getDescription() { } /** Gets the product price. @return the unit price */ public double getPrice() { } }
    62. 62. Method Documentation – Address class /** Describes a mailing address. */ public class Address { /** Formats the address. @return the address as a string with three lines */ public String format() { } }
    63. 63. Implementation <ul><li>Invoice aggregates Address and LineItem </li></ul><ul><li>Every invoice has one billing address </li></ul><ul><li>An invoice can have many line items: </li></ul>public class Invoice { . . . private Address billingAddress; private ArrayList<LineItem> items; }
    64. 64. Implementation <ul><li>A line item needs to store a Product object and quantity: </li></ul>public class LineItem { . . . private int quantity; private Product theProduct; }
    65. 65. Implementation <ul><li>The methods themselves are now very easy </li></ul><ul><li>Example: </li></ul><ul><ul><li>getTotalPrice of LineItem gets the unit price of the product and multiplies it with the quantity </li></ul></ul>/** Computes the total cost of this line item. @return the total price */ public double getTotalPrice() { return theProduct.getPrice() * quantity; }
    66. 66. Self Check <ul><li>Which class is responsible for computing the amount due? What are its collaborators for this task? </li></ul><ul><li>Why do the format methods return String objects instead of directly printing to System.out ? </li></ul>
    67. 67. Answers <ul><li>The Invoice class is responsible for computing the amount due. It collaborates with the LineItem class. </li></ul><ul><li>This design decision reduces coupling. It enables us to reuse the classes when we want to show the invoice in a dialog box or on a web page. </li></ul>
    68. 68. Suh’s Axioms of OOD <ul><li>The independence axiom: Maintain independence of components. Each component must satisfy its requirements without affecting other requirements. </li></ul><ul><li>The information axiom: Minimize the information content of the design. It is concerned with simplicity. Rely on Occam’s Razor </li></ul>
    69. 69. Occum’s Razor rule of simplicity <ul><li>The best designs usually involve the least complex code but not necessarily the fewest number of classes or methods. </li></ul><ul><li>Minimizing complexity should be the goal, because that produces the most easily maintained and enhanced application. </li></ul><ul><li>In an object-oriented system, the best way to minimize complexity is to use inheritance and the system’s built-in classes and to add as little as possible to what already is there. </li></ul>
    70. 70. Some Corollaries… <ul><li>Uncoupled design </li></ul><ul><li>Single purpose </li></ul><ul><li>Large number of simple classes </li></ul><ul><li>Strong mapping </li></ul><ul><li>Standardization </li></ul><ul><li>Design with inheritance </li></ul>
    71. 71. Uncoupled Design <ul><li>Coupling is a measure of the strength of association established by a connection from one object or software component to another. </li></ul><ul><li>Types </li></ul><ul><ul><li>Interaction coupling </li></ul></ul><ul><ul><ul><li>amount and complexity of messages between components. </li></ul></ul></ul><ul><ul><ul><li>Preferred to be minimal </li></ul></ul></ul><ul><ul><ul><li>What happens when high and low ? </li></ul></ul></ul><ul><ul><li>Inheritance coupling </li></ul></ul><ul><ul><ul><li>coupling between super and sub classes </li></ul></ul></ul><ul><ul><ul><li>coupling in terms of attributes and methods </li></ul></ul></ul><ul><ul><ul><li>Preferred to be high </li></ul></ul></ul><ul><ul><ul><li>What happens when high and low ? { override all, unused methods } </li></ul></ul></ul>
    72. 72. Cohesion <ul><li>Cohesion reflects the “single-purposeness” of an object. </li></ul><ul><li>Highly cohesion  Lower coupling </li></ul><ul><li>Method cohesion: method carrying one function. </li></ul><ul><li>A method that carries multiple functions is undesirable. </li></ul><ul><li>Class cohesion: All the class’s methods and attributes are highly cohesive, meaning to be used by internal methods or derived classes’ methods. </li></ul>
    73. 73. Corollary 2: Single Purpose <ul><li>Every class should be clearly defined and necessary in the context of achieving the system’s goals. </li></ul><ul><li>When we document a class, we should be able to explain its purpose in a sentence or two. </li></ul><ul><li>If we cannot, then the class should be subdivided into independent pieces. </li></ul><ul><li>Each method must provide only one service. </li></ul><ul><li>Each method should be of moderate size, no more than a page; half a page is better. </li></ul>
    74. 74. Achieving Multiple Inheritance <ul><li>What is Single inheritance? </li></ul><ul><li>What is the problem with Multiple Inheritance ? </li></ul><ul><li>What is the ideal case for MI ? </li></ul><ul><li>In C++ objects can inherit behavior from unrelated areas of the class tree. </li></ul><ul><li>How to determine which behavior to get from which class, particularly when several ancestors define the same method. </li></ul><ul><li>Virtual Inheritance !!?? </li></ul>
    75. 75. Class Visibility <ul><li>Purpose of Access Specifiers ? </li></ul><ul><li>Difference between c++ struct and class ? </li></ul><ul><li>The class’s protocol or the messages that a class understands, can be hidden from other objects (private protocol) or made available to other objects (public protocol). </li></ul><ul><li>Public protocols define the functionality and external messages of an object. </li></ul><ul><li>Private protocols define the implementation of an object. </li></ul><ul><li>The lack of well-designed protocol can manifest itself as encapsulation leakage. It happens when details about a class’s internal implementation are disclosed through the interface </li></ul>
    76. 76. Design patterns <ul><li>A design pattern is a way of reusing abstract knowledge about a problem and its solution </li></ul><ul><ul><li>Patterns are devices that allow programs to share knowledge about their design </li></ul></ul><ul><li>A pattern is a description of the problem and the essence of its solution </li></ul><ul><ul><li>Documenting patterns is one way to reuse and share the information about how it is best to solve a specific design problem </li></ul></ul><ul><li>A pattern should be sufficiently abstract to be reused in different settings </li></ul><ul><li>Patterns often rely on object characteristics such as inheritance and polymorphism </li></ul>
    77. 77. Pattern elements <ul><li>Name </li></ul><ul><ul><li>A meaningful pattern identifier </li></ul></ul><ul><li>Problem description </li></ul><ul><li>Solution description </li></ul><ul><ul><li>Not a concrete design but a template for a design solution that can be instantiated in different ways </li></ul></ul><ul><li>Consequences </li></ul><ul><ul><li>The results and trade-offs of applying the pattern </li></ul></ul>
    78. 78. Types of Patterns <ul><li>Creational </li></ul><ul><ul><li>Abstract Factory </li></ul></ul><ul><li>Structural </li></ul><ul><ul><li>Adapter </li></ul></ul><ul><ul><li>Façade </li></ul></ul><ul><ul><li>Proxy </li></ul></ul><ul><li>Behavioral </li></ul><ul><ul><li>Observer </li></ul></ul><ul><ul><li>Mediator </li></ul></ul>
    79. 79. Patterns by Example: Multiple displays enabled by Observer A=10% B=40% C=30% D=20% Application data A B C D A D C B Relative Percentages Y 10 40 30 20 X 15 35 35 15 Z 10 40 30 20 A B C D Change notification Requests, modifications
    80. 80. The Observer pattern <ul><li>Name </li></ul><ul><ul><li>Observer </li></ul></ul><ul><li>Description </li></ul><ul><ul><li>Separates the display of object state from the object itself </li></ul></ul><ul><li>Problem description </li></ul><ul><ul><li>Used when multiple displays of state are needed </li></ul></ul><ul><li>Solution description </li></ul><ul><ul><li>See slide with UML description </li></ul></ul><ul><li>Consequences </li></ul><ul><ul><li>Optimisations to enhance display performance are impractical </li></ul></ul>
    81. 81. The Observer pattern observerState= subject  getState(); Subject attach (Observer) detach (Observer) Notify () Observer Update() Concrete Observer Update() observerState Concrete Subject GetState() SetState() subjectState observers subject For all x in observers{ x  Update(); }
    82. 82. The Mediator Pattern <ul><li>Description </li></ul><ul><ul><li>Define an object that encapsulates how a set of objects interact </li></ul></ul><ul><ul><li>Mediator promotes loose coupling by keeping objects from referring to each other explicitly </li></ul></ul><ul><ul><li>It lets you vary their interaction independently </li></ul></ul><ul><li>Applicability </li></ul><ul><ul><li>Complex interaction exists </li></ul></ul><ul><ul><li>You do not want to bury the interaction in the objects </li></ul></ul><ul><ul><li>Distributed behavior should be customizable without a lot of sub classing </li></ul></ul><ul><li>Consequences </li></ul><ul><ul><li>Limits sub classing </li></ul></ul><ul><ul><li>Decouples colleagues </li></ul></ul><ul><ul><li>Simplifies object protocols </li></ul></ul><ul><ul><li>Abstracts how objects cooperate </li></ul></ul><ul><ul><li>Centralizes control </li></ul></ul>
    83. 83. The Mediator Pattern
    84. 84. The Façade Pattern <ul><li>Description </li></ul><ul><ul><li>Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. </li></ul></ul><ul><li>Applicability </li></ul><ul><ul><li>Need to provide a simple interface to a complex system </li></ul></ul><ul><ul><li>Need to decouple a subsystem from its clients </li></ul></ul><ul><ul><li>Need to provide an interface to a software layer </li></ul></ul><ul><li>Consequences </li></ul><ul><ul><li>Shields clients from subsystem components </li></ul></ul><ul><ul><li>Promotes weak coupling between the subsystem and its clients </li></ul></ul>
    85. 85. Facade Pattern: Problem Subsystem classes Client Classes Need to communicate with
    86. 86. Facade Pattern: Solution Subsystem classes Fac ade Client Classes
    87. 87. The Façade Pattern
    88. 88. The Proxy Pattern <ul><li>Description </li></ul><ul><ul><li>Provide a surrogate or placeholder for another object to control access to it. </li></ul></ul><ul><li>Applicability </li></ul><ul><ul><li>Remote proxies can hide the fact that a real object is in another address space </li></ul></ul><ul><ul><li>Virtual proxies can create expensive objects on demand. </li></ul></ul><ul><ul><li>Protection proxies can control access to an object. </li></ul></ul><ul><ul><li>Smart references can perform additional action above a simple pointer </li></ul></ul>
    89. 89. The Proxy Pattern
    90. 90. The Adapter Pattern <ul><li>Description </li></ul><ul><ul><li>Convert the interface of a class into another interface clients expect </li></ul></ul><ul><ul><li>Adapter lets classes work together that could not otherwise because of incompatible interfaces </li></ul></ul><ul><li>Applicability </li></ul><ul><ul><li>Need to use an existing class whose interface does not match </li></ul></ul><ul><ul><li>Need to make use of incompatible classes </li></ul></ul><ul><li>Consequences </li></ul><ul><ul><li>Class adapter commits to the concrete Adapter class </li></ul></ul><ul><ul><li>Class adapter introduces only one object and no pointer indirection </li></ul></ul>
    91. 91. The Adapter Pattern
    92. 92. The Abstract Factory Pattern <ul><li>Description </li></ul><ul><ul><li>Provides an interface for creating families of related or dependent objects without specifying their concrete classes. </li></ul></ul><ul><li>Applicability </li></ul><ul><ul><li>Need to abstract from details of implementation of products </li></ul></ul><ul><ul><li>Need to have multiple families of products </li></ul></ul><ul><ul><li>Need to enforce families of products that must be used together </li></ul></ul><ul><ul><li>Need to hide product implementations and just present interfaces </li></ul></ul><ul><li>Consequences </li></ul><ul><ul><li>Isolates concrete classes </li></ul></ul><ul><ul><li>Makes exchanging product families easy </li></ul></ul><ul><ul><li>Promotes consistency among products </li></ul></ul><ul><ul><li>Supporting new kinds (in each family) of products is difficult </li></ul></ul>
    93. 93. The Abstract Factory Pattern AbstractFactory CreateProductA() CreateProductB() ConcreteFactory1 Client ProductA1 ProductA2 AbstractProductA ProductB2 ProductB1 AbstractProductB ConcreteFactory2 CreateProductA() CreateProductB()
    94. 94. Abstract Factory Example WidgetFactory CreateScrollbar() CreateWindow() Window ScrollBar WWidgetFactory MacWidgetFactory Client WWindow MacWindow MacScrollBar WScrollBar One for each standard.
    95. 95. <ul><li>What is dependency management? </li></ul><ul><li>What bearing does DM have on software? </li></ul><ul><li>What is the result of poor DM? </li></ul><ul><li>What is the advantage of good DM? </li></ul>Dependency Management
    96. 96. What is dependency management? <ul><li>A simple idea - as interdependencies increase, features like reusability, flexibility, and maintainability decrease. </li></ul><ul><li>Dependency management is controlling interdependencies. </li></ul>
    97. 97. What bearing does DM have on software? <ul><li>Coupling and cohesion are the eternal concerns of software development </li></ul><ul><li>One can say that OO is just a set of tools and techniques for Dependency Management </li></ul>
    98. 98. What is the penalty for practicing poor DM? <ul><li>It is rigid </li></ul><ul><li>It is fragile </li></ul><ul><li>It is not reusable </li></ul><ul><li>It has high viscosity </li></ul>A system with poor dependency structure will typically exhibit these four negative traits:
    99. 99. It is Rigid <ul><li>The impact of a change cannot be predicted </li></ul><ul><li>If not predicted, it cannot be estimated </li></ul><ul><li>Time and cost cannot be quantified </li></ul><ul><li>Managers become reluctant to authorize change </li></ul><ul><li>Official Rigidity for “Roach Motel” modules </li></ul>Rigidity is the inability to be changed
    100. 100. Changes with Rigidity The System Officially Rigid Area Where the change should be made Where the change must be made now Are we containing risk, or spreading rot?
    101. 101. It is Fragile <ul><li>A single change requires a cascade of subsequent changes </li></ul><ul><li>New errors appear in areas that seem unconnected to the changed areas </li></ul><ul><li>Quality is unpredictable. </li></ul><ul><li>The development team loses credibility </li></ul>Software changes seem to exhibit non-local effects
    102. 102. Increasing Risk Defects v. Cumulative Modifications Systems tend to become increasingly fragile over time. Intentional, planned partial rewrites may be necessary to sustain growth and maintenance. Changes Probability of introducing a bug 1.0
    103. 103. It is not reusable <ul><li>Desirable parts of the design are dependent upon undesirable parts </li></ul><ul><li>The work and risk of extracting the desirable part may exceed the cost of redeveloping from scratch. </li></ul>
    104. 104. The Trailer The Trailer
    105. 105. It has high viscosity <ul><li>When the “right changes” are much more difficult than hacking, the viscosity of the system is high. </li></ul><ul><li>Over time, it will become increasingly difficult to continue developing the product. </li></ul>Viscosity is resistance to fluid motion.
    106. 106. What is the benefit of good DM? Interdependencies are managed, with firewalls separating aspects that need to vary independently. Fewer Trailers Slow the rot More Flexible Less fragile, the bugs are boxed in Easier to reuse Easier to make the right change
    107. 107. What causes “Code Rot”? <ul><li>A case study “The Copy Routine” </li></ul>It’s been blamed on stupidity, lack of discipline, and phases of the moon, but...
    108. 108. First Version All designs start well The program is an overnight success! How could it be more simple, elegant, and maintainable? void copy(void) { int ch; while( (ch=ReadKeyboard()) != EOF) WritePrinter(ch); }
    109. 109. Second Version <ul><li>We sometimes want to read from paper tape reader. </li></ul><ul><li>We could put a parameter in the call, but we have hundreds of users already! </li></ul><ul><li>No big deal, this is just an exception… we can make it work. </li></ul>Oh, no! Nobody said the requirements might change!
    110. 110. Second Version Design bool GtapeReader = false; // remember to clear void copy(void) { int ch; while( (ch=GtapeReader ? ReadTape() : ReadKeyboard()) != EOF) WritePrinter(ch); }
    111. 111. Third Version How unexpected! Requirements changed again! bool GtapeReader = false; Bool GtapePunch = false; // remember to clear void copy(void) { int ch; while( (ch=GtapeReader ? ReadTape() : ReadKeyboard()) != EOF) GtapePunch ? WritePunch(ch) : WritePrinter(ch); } It seems that sometimes we need to write to a paper tape punch. We’ve had this problem before, and just added a flag. Looks like it should work again.
    112. 112. Example of a Good Design First and only version. void Copy() { int c; while( (c=getchar()) != EOF) putchar(c); } But wait! Aren’t we supposed to be learning OO design? This isn’t OO is it?
    113. 113. … is it? <ul><li>FILE is an abstraction </li></ul><ul><ul><li>It represents some kind of byte stream </li></ul></ul><ul><ul><li>It has many variations </li></ul></ul><ul><li>It has methods </li></ul><ul><ul><li>Read, Write, getchar, putchar, etc </li></ul></ul><ul><ul><li>The methods are *dynamically* bound </li></ul></ul>It is a small program based on abstractions! FILE is a class, just implemented differently.
    114. 114. Rephrased in OO interface Reader { char read(); } interface Writer { void write(char c); } public class Copy { Copy(Reader r, Writer w) { itsReader = r; itsWriter = w; } public void copy() { int c; while( (c==itsReader.read()) != EOF ) itsWriter.write(c); } private Reader itsReader; private Writer itsWriter; }
    115. 115. Class Design Principles <ul><li>S RP: The Single Responsibility Principle </li></ul><ul><li>O CP: The Open/Closed Principle </li></ul><ul><li>L SP: The Liskov Substitution Principle </li></ul><ul><li>I SP: The Interface Segregation Principle </li></ul><ul><li>D IP: The Dependency Inversion Principle </li></ul>From: Agile Software Development: Principles, Patterns, and Practices. Robert C. Martin, Prentice Hall, 2002.
    116. 116. The Single Responsibility Principle <ul><li>A class should have one, and only one, reason to change. </li></ul>
    117. 117. Open/Closed Principle <ul><li>A principle which states that we should add new functionality by adding new code, not by editing old code. </li></ul><ul><li>Defines a lot of the value of OO programming </li></ul><ul><li>Abstraction is the key </li></ul>“ Modules should be open for extension, but closed for modification” -Bertrand Meyer
    118. 118. Abstraction is Key <ul><li>Client/Server relationships are “open” </li></ul><ul><li>Changes to servers cause changes to clients </li></ul><ul><li>Abstract servers “close” clients to changes in implementation. </li></ul>Abstraction is the most important word in OOD
    119. 119. The Shape Example <ul><li>Procedural (not closed) implementation </li></ul><ul><li>OO (closed) implementation </li></ul>
    120. 120. Procedural (open) version enum ShapeType {circle, square}; struct Shape {enum ShapeType itsType;}; struct Circle { enum ShapeType itsType; double itsRadius; Point itsCenter; }; void DrawCircle(struct Circle*) struct Square { enum ShapeType itsType; double itsSide; Point itsTopLeft; }; void DrawSquare(struct Square*) #include <Shape.h> #include <Circle.h> #include <Square.h> typedef struct Shape* ShapePtr; void DrawAllShapes(ShapePtr list[], int n) { int i; for( i=0; i< n, i++ ) { ShapePtr s = list[i]; switch ( s->itsType ) { case square: DrawSquare((struct Square*)s); break; case circle: DrawCircle((struct Circle*)s); break; } } } Shape.h Circle.h Square.h DrawAllShapes.c
    121. 121. What is wrong with the code? <ul><li>DrawAllShapes is not closed. </li></ul><ul><ul><li>Switch/case tend to recur in diverse places. </li></ul></ul><ul><ul><li>If we add a shape, we add to the switch/case </li></ul></ul><ul><ul><li>All switch/case statements must be found and editd. </li></ul></ul><ul><ul><li>Switch/Case statements are seldom this tidy </li></ul></ul><ul><ul><li>When we add to the enum, we must rebuild everything </li></ul></ul><ul><li>The software is both rigid and brittle </li></ul>It can be demonstrated to work. Isn’t that the important thing?
    122. 122. A Closed Implementation Class Shape { public: virtual void Draw() const =0; }; #include <Shape.h> void DrawAllShapes(Shape* list[],int n) { for(int i=0; i< n; i++) list[i]->draw(); } Shape.h DrawAllShapes.cpp Circle.h Square.h Class Square: public Shape { public: virtual void Draw() const; }; Class Circle: public Shape { public: virtual void Draw() const; };
    123. 123. Strategic Closure <ul><li>Closure Against What? </li></ul><ul><ul><li>Closure is strategic. You have to choose which changes you’ll isolate yourself against. </li></ul></ul><ul><ul><li>What if we have to draw all circles first? Now DrawAllShapes must be edited (or we have to hack something) </li></ul></ul><ul><li>Opened Where? </li></ul><ul><ul><li>Somewhere, someone has to instantiate the individual shapes. </li></ul></ul><ul><ul><li>It’s best if we can keep the dependencies confined </li></ul></ul><ul><li>Use abstraction to gain explicit closure </li></ul><ul><ul><li>provide class methods which can be dynamically invoked </li></ul></ul><ul><ul><ul><li>to determine general policy decisions </li></ul></ul></ul><ul><ul><ul><li>e.g. draw Squares before Circles </li></ul></ul></ul><ul><ul><li>design using abstract ancestor classes </li></ul></ul><ul><li>Use &quot;Data-Driven&quot; approach to achieve closure </li></ul><ul><ul><li>place volatile policy decisions in a separate location </li></ul></ul><ul><ul><ul><li>e.g. a file or a separate object </li></ul></ul></ul><ul><ul><li>minimizes future change locations </li></ul></ul>No program is 100% closed.
    124. 124. Liskov Substitution Principle <ul><li>All derived classes must be substitutable for their base classes </li></ul><ul><li>This principle guides us in the creation of abstractions. </li></ul>Derived classes must be usable through the base class interface, without the need for the user to know the difference.
    125. 125. Square/Rectangle A square is-a rectangle, right? So lets consider Square as a subtype of Rectangle. void Square::SetWidth(double w) { width = w; height = w; } void Square::SetHeight(double h) { width = h; height = h; } We can make it work: Uh, oh. This doesn’t quite seem to fit
    126. 126. Substitution… denied! <ul><li>It is reasonable for users of a rectangle to expect that height and width may change independently. </li></ul><ul><li>These expectations are preconditions and postconditions </li></ul><ul><ul><li>Bertrand Meyer calls it “Design by Contract” </li></ul></ul><ul><ul><li>Post condition contract for rectangle is </li></ul></ul><ul><ul><ul><li>width = new Width </li></ul></ul></ul><ul><ul><ul><li>height = old height </li></ul></ul></ul><ul><li>Square violates Rectangle’s contract </li></ul>
    127. 127. Liskov Substitution Principle <ul><li>A client of rectangle expects height and width to be changed independently </li></ul><ul><ul><li>void setAspectRatio( Rectange* r, double ratio ); </li></ul></ul><ul><li>By deriving Square from Rectangle, we are allowing someone to set the aspect ratio of a Square ! </li></ul><ul><li>We can still make it work </li></ul><ul><ul><li>if ( typeid(r) == typeid(Rectangle) ) </li></ul></ul><ul><ul><li>Violates Open/Closed Principle ! </li></ul></ul>
    128. 128. Liskov Substitution Principle <ul><li>Design by Contract </li></ul><ul><ul><li>Bertrand Meyer </li></ul></ul><ul><ul><li>Pre-conditions, Post-conditions, invariants </li></ul></ul><ul><li>Rectangle's postconditions for setWidth() </li></ul><ul><ul><li>width = newWidth </li></ul></ul><ul><ul><li>length = oldLength </li></ul></ul><ul><li>Square can require no more of clients, nor promise any less </li></ul><ul><ul><li>Doesn't maintain invariant of length </li></ul></ul><ul><ul><li>Violates the contract </li></ul></ul>
    129. 129. Design by Contract <ul><li>Advertised Behavior of an object: </li></ul><ul><ul><li>advertised Requirements ( Preconditions ) </li></ul></ul><ul><ul><li>advertised Promises ( Postconditions ) </li></ul></ul><ul><li>When redefining a method in a derivate class, you may only replace its precondition by a weaker one , and </li></ul><ul><li>its postcondition by a stronger one </li></ul><ul><ul><ul><ul><ul><li>B. Meyer , 1988 </li></ul></ul></ul></ul></ul><ul><li>Derived class services should require no more and promise no less </li></ul>int Base::f(int x); // REQUIRE: x is odd // PROMISE: return even int int Derived::f(int x); // REQUIRE: x is int // PROMISE: return 8
    130. 130. LSP is about Semantics and Replacement <ul><li>The meaning and purpose of every method and class must be clearly documented </li></ul><ul><ul><li>Lack of user understanding will induce de facto violations of LSP </li></ul></ul><ul><li>Replaceability is crucial </li></ul><ul><ul><li>Whenever any class is referenced by any code in any system, </li></ul></ul><ul><ul><li>any future or existing subclasses of that class must be 100% replaceable </li></ul></ul><ul><ul><li>Because, sooner or later, someone will substitute a subclass; </li></ul></ul><ul><ul><ul><li>it’s almost inevitable. </li></ul></ul></ul>
    131. 131. Dependency Inversion Principle Details should depend on abstractions. Abstractions should not depend on details. V.
    132. 132. Dependency Inversion Principle I. High-level modules should not depend on low-level modules. Both should depend on abstractions. II. Abstractions should not depend on details. Details should depend on abstractions R. Martin , 1996 <ul><li>OCP states the goal ; DIP states the mechanism </li></ul><ul><li>A base class in an inheritance hierarchy should not know any of its subclasses </li></ul><ul><li>Modules with detailed implementations are not depended upon, but depend themselves upon abstractions </li></ul>
    133. 133. Procedural vs. OO Architecture Procedural Architecture Object-Oriented Architecture
    134. 134. DIP Applied on Example Copy Reader Writer Keyboard Reader Printer Writer class Reader { public: virtual int read()=0; }; class Writer { public: virtual void write(int)=0; }; void Copy(Reader& r, Writer& w){ int c; while((c = r.read()) != EOF) w.write(c); } Disk Writer
    135. 135. Interface Segregation Principle <ul><li>Sometimes class methods have various groupings. </li></ul><ul><li>These classes are used for different purposes. </li></ul><ul><li>Not all users rely upon all methods. </li></ul><ul><li>This lack of cohesion can cause serious dependency problems </li></ul><ul><li>These problems can be refactored away. </li></ul>Helps deal with “fat” or inappropriate interfaces
    136. 136. Interface Pollution by “collection” Distinct clients of our class have distinct interface needs.
    137. 137. A Segregated Example
    138. 138. ATM UI Example
    139. 139. A Segregated ATM UI Example
    140. 140. Logger Example
    141. 141. Four Class Design Principles - Review <ul><li>OCP: Extend function without editing code </li></ul><ul><li>LSP: Child instances substitute cleanly for base </li></ul><ul><li>DIP: Depend on abstractions instead of details </li></ul><ul><li>ISP: Split interfaces to manage dependencies </li></ul>
    142. 142. Thank you <ul><li>Please write you queries to </li></ul><ul><li>[email_address] </li></ul><ul><li>www.sudarsun.in </li></ul>