7 ooad


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

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

No notes for slide

7 ooad

  1. 1. OO Design 1Object Oriented Design
  2. 2. OO Design 2Object Orientation Traditional procedural systems separatedata and procedures, and model theseseparately Object orientation –views data andfunctions together; data abstraction is thebasis The purpose of OO design is to define theclasses in the system to be built and theirrelationships
  3. 3. OO Design 3OOA and OOD OO techniques can be used in analysis(requirements) as well as design The methods and notations are similar In Object Oriented Analysis (OOA) we model theproblem, while in Object Oriented Deisgn (OOD)we model the solution Often OOA structures are subsumed in thesolution domain structures The line between OOA and OOD is not fixed
  4. 4. OO Design 4OOA and OOD…
  5. 5. OO Design 5OO Concepts Encapsulation – grouping of related ideasinto one unit which we can refer to by asingle name Eg. procedures, functions, packages In OO, object is the unit; encapsulatesstate and provides interface to access andmodify
  6. 6. OO Design 6OO Concepts.. Information hiding – use encapsulation torestrict external visibility OO encapsulates the data, provides limitedaccess, visibility Information hiding can be provided withoutOO – is an old concept
  7. 7. OO Design 7OO Concepts… State retention – functions, procedures donot retain state; an object is aware of itspast and maintains state Identity – each object can be identified andtreated as a distinct entity Behavior – state and services togetherdefine the behavior of an object, or how anobject responds
  8. 8. OO Design 8OO Concepts.. Messages – through which a sender objectconveys to a target object a request For requesting O1 must have – a handle for O2 name of the operation information on operations that O2 requires General format O2.method(args)
  9. 9. OO Design 9OO Concepts.. Classes – a class is a stencil from which objectsare created; defines the structure and services. Aclass has An interface which defines which parts of an object canbe accessed from outside Body that implements the operations Instance variables to hold object state A class defines the attributes and operations Objects and classes are different; class is a type,object is an instance State and identity is of objects
  10. 10. OO Design 10OO Concepts – access Operations in a class can be Public: accessible from outside Private: accessible only from within the class Protected: accessible from within the class andfrom within subclasses There are some constructor and destructoroperations Used to modify attributes
  11. 11. OO Design 11Inheritance Inheritance is unique to OO not there in function-oriented languages/models Inheritance by class B from class A is the facilityby which B implicitly gets the attributes andoperations of A as part of itself Attributes and methods of A are reused by B When B inherits from A, B is the subclass orderived class and A is the base class orsuperclass
  12. 12. OO Design 12Inheritance.. A subclass B generally has a derived part(inherited from A) and an incremental part(is new) Hence, B needs to define only theincremental part Creates an “is-a” relationship objects of type B are also objects of type A
  13. 13. OO Design 13Inheritance…
  14. 14. OO Design 14Inheritance… The inheritance relationship between classesforms a class hierarchy In models, hierarchy should represent the naturalrelationships present in the problem domain In a hierarchy, all the common features can beaccumulated in a superclass An existing class can be a specialization of anexisting general class – is also calledgeneralization-specialization relationships
  15. 15. OO Design 15Hierarchy Class ExampleAttributesSubclass has access to theseOperationsSubclass has access to these
  16. 16. OO Design 16Inheritance… Strict inheritance – a subclass takes allfeatures of parent class Only adds features to specialize it Non-strict: when some of the features havebeen redefined Strict inheritance supports “is-a” cleanlyand has fewer side effects
  17. 17. OO Design 17Inheritance… Single inheritance – a subclass inheritsfrom only one superclass Class hierarchy is a tree Multiple inheritance – a class inherits frommore than one class Can cause runtime conflicts Repeated inheritance - a class inherits from aclass but from two separate paths
  18. 18. OO Design 18Inheritance and Polymorphism Inheritance brings polymorphism, i.e. an objectcan be of different types An object of type B is also an object of type A Hence an object has a static type and a dynamictype Implications on type checking Also brings dynamic binding of operations which allowswriting of general code where operations do differentthings depending on the type
  19. 19. OO Design 19Module Level Concepts Basic modules are classes During design key activity is to specify theclasses in the system being built Correctness of design is fundamental But design should also be “good” –efficient, modifiable, stable, … Can evaluate a design using coupling,cohesion, and open-closed principle
  20. 20. OO Design 20Coupling Coupling is an inter-module concept,captures the strength of interconnectionbetween modules More tightly coupled the modules, the morethey depend on each other, more difficult tomodify one Low coupling is desirable for makingsystems understandable and modifiable In OO, three types of coupling exists –interaction, component, and inheritance
  21. 21. OO Design 21Coupling… Interaction coupling occurs due to methodsof a class invoking methods of otherclasses Like calling of functions Worst form if methods directly access internalparts of other methods Still bad if methods directly manipulatevariables of other classes Passing information through temporaryvariables is also bad
  22. 22. OO Design 22Coupling… Least interaction coupling if methodscommunicate directly with parameters With least number of parameters With least amount of information being passed With only data being passed I.e. methods should pass the least amountof data, with least number of parameters
  23. 23. OO Design 23Coupling… Component coupling – when a class A hasvariables of another class C A has instance variables of C A has some parameters of type C A has a method with a local variable of type C When A is coupled with C, it is coupled withall subclasses of C as well Component coupling will generally implythe presence of interaction coupling also
  24. 24. OO Design 24Coupling… Inheritance coupling – two classes arecoupled if one is a subclass of other Worst form – when subclass modifies asignature of a method or deletes a method Coupling is bad even when same signaturebut a changed implementation Least, when subclass only adds instancevariables and methods but does not modifyany
  25. 25. OO Design 25Cohesion Cohesion is an intra-module concept Focuses on why elements are together Only elements tightly related should exist together in amodule This gives a module clear abstraction and makes iteasier to understand Higher cohesion leads to lower coupling – manyinteracting elements are in the module Goal is to have higher cohesion in modules Three types of cohesion in OO – method, class,and inheritance
  26. 26. OO Design 26Cohesion… Method cohesion – why different codeelements are together in a method (likecohesion in functional modules) Highest form is if each method implements aclearly defined function with all elementscontributing to implementing this function Should be able to state what the module doesby a simple statement
  27. 27. OO Design 27Cohesion… Class cohesion – why different attributesand methods are together in a class A class should represent a single concept withall elements contributing towards it Whenever multiple concepts encapsulated,cohesion is not as high A symptom of multiple concepts – differentgroups of methods accessing different subsetsof attributes
  28. 28. OO Design 28Cohesion… Inheritance cohesion – focuses on whyclasses are together in a hierarchy Two reasons for subclassinggeneralization-specializationreuse Cohesion is higher if the hierarchy is forproviding generalization-specialization
  29. 29. OO Design 29Friday
  30. 30. OO Design 30Open-closed Principle Principle: Classes should be open forextension but closed for modification Behavior can be extended to accommodatenew requirements, but existing code is notmodified I.e. allows addition of code, but not modificationof existing code Minimizes risk of having existing functionalitystop working due to changes – a very importantconsideration while changing code Good for programmers as they like writing newcode
  31. 31. OO Design 31Open-closed Principle… In OO this principle is satisfied by usinginheritance and polymorphism Inheritance allows creating a new class toextend behavior without changing theoriginal class This can be used to support the open-closed principle Consider example of a client object whichinteracts with a printer object for printing
  32. 32. OO Design 32Example
  33. 33. OO Design 33Example.. Client directly calls methods on Printer1 If another printer is to be allowed A new class Printer2 will be created But the client will have to be changed if it wantsto use Printer 2 Alternative approach Have Printer1 a subclass of a general Printer For modification, add another subclass Printer 2 Client does not need to be changed
  34. 34. OO Design 34Example…
  35. 35. OO Design 35Liskov’s Substitution Principle Principle: Program using object O1 of baseclass C should remain unchanged if O1 isreplaced by an object of a subclass of C If hierarchies follow this principle, the open-closed principle gets supported
  36. 36. OO Design 36Unified Modeling Language (UML)and Modeling UML is a graphical notation useful for OOanalysis and design Allows representing various aspects of thesystem Various notations are used to build differentmodels for the system OOAD methodologies use UML torepresent the models they create
  37. 37. OO Design 37Modeling Modeling is used in many disciplines –architecture, aircraft building, … A model is a simplification of reality “All models are wrong, some are useful” A good model includes those elements thathave broad effect and omits minorelements A model of a system is not the system!
  38. 38. OO Design 38Why build models? Models help us visualize a system Help specify the system structure Gives us a template that can guide theconstruction Document the decisions taken and theirrationale
  39. 39. OO Design 39Modeling Every complex system requires multiplemodels, representing different aspects These models are related but can bestudied in isolation Eg. Architecture view, electrical view,plumbing view of a building Model can be structural, or behavioral
  40. 40. OO Design 40Views in an UML Different views A use case view A design view A process view Implementation view Deployment view We will focus primarily on models fordesign class diagram, interaction diagram, etc.
  41. 41. OO Design 41Class Diagrams Classes are the basic building blocks of anOO system as classes are theimplementation units also Class diagram is the central piece in an OOdesign. It specifies Classes in the system Association between classes Subtype, supertype relationship
  42. 42. OO Design 42Class Diagram… Class itself represented as a box withname, attributes, and methods There are conventions for naming If a class is an interface, this can bespecified by <<interface>> stereotype Properties of attributes/methods can bespecified by tags between { }
  43. 43. OO Design 43Class – example
  44. 44. OO Design 44Generalization-Specialization This relationship leads to class hierarchy Can be captured in a class diagram Arrows coming from the subclass to thesuperclass with head touching super Allows multiple subclasses If specialization is done on the basis of somediscriminator, arrow can be labeled
  45. 45. OO Design 45Example – class hierarchy
  46. 46. OO Design 46Association/aggregation Classes have other relationships Association: when objects of a class needservices from other objects Shown by a line joining classes Multiplicity can be represented Aggregation: when an object is composedof other objects Captures part-whole relationship Shown with a diamond connecting classes
  47. 47. OO Design 47Example – association/aggregation
  48. 48. OO Design 48Interaction Diagrams Class diagrams represent static structure ofthe system (classes and their relationships) Do not model the behavior of system Behavioral view shows how objects interact for performingactions (typically a use case) Interaction is between objects, not classes Interaction diagram in two styles Collaboration diagram Sequence diagram Two are equivalent in power
  49. 49. OO Design 49Sequence Diagram Objects participating in an interaction areshown at the top For each object a vertical bar represents itslifeline Message from an object to another,represented as a labeled arrow If message sent under some condition, itcan be specified in bracket Time increases downwards, ordering ofevents is captured
  50. 50. OO Design 50Example – sequence diagramTimeObjects participating in an interaction
  51. 51. OO Design 51Collaboration diagram Also shows how objects interact Instead of timeline, this diagram looks morelike a state diagram Ordering of messages captured bynumbering them Is equivalent to sequence diagram inmodeling power
  52. 52. OO Design 52Example – collaboration diag
  53. 53. OO Design 53Other Diagrams Class diagram and interaction diagramsmost commonly used during design There are other diagrams used to builddifferent types of models
  54. 54. OO Design 54State Diagrams Dynamic model to represent behavior of anindividual object or a system Shows the states of an object andtransitions between them Helps understand the object – focus onlyon the important logical states State diagrams can be very useful forautomated and systematic testing
  55. 55. OO Design 55State diagram of a stackpushpop
  56. 56. OO Design 56Activity Diagrams Another method for modeling the dynamicbehavior Describes the sequence of activities, andparallel behavior in a system Activity represented by ovals, dependenceshown by inputs/outputs Variant of a state diagram – captures thestate of the system and transitions
  57. 57. OO Design 57Other Diagrams Instead of objects/classes, can representcomponents, packages, subsystems These are useful for developingarchitecture structures UML is extensible – can model a new butsimilar concept by using stereotypes (byadding <<name>>) Tagged values can be used to specifyadditional properties, e.g. private,readonly.. Notes can be added
  58. 58. OO Design 58Other symbols
  59. 59. OO Design 59Design using UML Many OOAD methodologies have beenproposed They provide some guidelines on the stepsto be performed Basic goal is to identify classes, understandtheir behavior, and relationships Different UML models are used for this Often UML is used, methodologies are notfollowed strictly
  60. 60. OO Design 60Design using UML Basic steps Identify classes, attributes, and operations fromuse cases Define relationships between classes Make dynamic models for key use cases anduse them to refine class diagrams Make a functional model and use it to refine theclasses Optimize and package Class diagrams play the central role; classdefinition gets refined as we proceed
  61. 61. OO Design 61Success Scenario Customer read the menu Customer places the order Order is sent to the kitchen for preparation Ordered items are served Customer requests for a bill for the order Bill is prepared for this order Customer is given the bill Customer pays the bill
  62. 62. OO Design 62Restaurant example: Initial classes
  63. 63. OO Design 63
  64. 64. OO Design 64Restaurant example: a sequence diagram
  65. 65. OO Design 65Example: Word CountProblem System prompts for the file name; userenters the file name System checks for existence of file System reads the words from the file Systems prints the count
  66. 66. OO Design 66Example: Word Count Problem…HistoryaddWord()exists()Filenamegetword()isEof()Wordstringsetstring()getstring()Countercountincrement()display()
  67. 67. OO Design 67Example: Word Count Problem…ReadFileGetwordsCheckForUniquenessAdd toHistoryIncrementCount
  68. 68. OO Design 68Monday Object Oriented Design Covered concepts Classes and objects Encapsulation State, behavior, identity Relationships among objects Inheritance and polymorphism Covered constraints Coupling Cohesion Covered tools Class diagrams Sequence diagrams
  69. 69. OO Design 69Metrics Weighted Methods per Class (WMC) Complexity of a class depends on number ofclasses and their complexity Suppose class C has methods M1, M2, …, Mn Suppose complexity of methods is c1, c2…determined by some functional complexity metric WMC = Σ ciIf the complexity of each method is considered 1,WMC gives the total number of methods in the class Large WMC might mean that the class is morefault-prone
  70. 70. OO Design 70Metrics… The deeper a class is in a class hierarchy More methods to reuse – larger reusepotential Increased coupling – harder to make change Depth of Inheritance (DIT) Tree DIT of class C in an inheritance hierarchytree is depth from the root classShortest path from root to node C DIT is significant in predicting faultproneness
  71. 71. OO Design 71Metrics… Number of Children (NOC) Number of immediate subclasses of C Evaluates the degree of reuse Higher NOC indicates reuse of definitions insuperclass by a larger number of subclasses Indicates influence of a class on other elementsLarger influence, more important to get designcorrect Higher NOC classes are less defect-proneNOC is only measuring structure, not inheritance
  72. 72. OO Design 72Metrics… Coupling Between Classes (CBC) Reduces modularity and makes module modificationharder CBC = Number of classes to which this class iscoupledTwo classes are coupled if methods of one use methods orinstance variables of other Can be determined from codeThere are indirect forms of coupling that cannot be staticallydetermined (e.g., pointers) Can predict fault proneness of classes, particular userinterface classes
  73. 73. OO Design 73Metrics… Response for a Class (RFC) The total number of methods that can be invoked froman object of this class RFC of C is cardinality of the response set for a classSet of all methods that can be invoked if a message is sent toan object of this class All methods of C as well as other classes the methods of C sendmessagesEven if CBC of a class is 1, RBC may be high Captures the strength of connections Harder to test classes with high RFC
  74. 74. OO Design 74Metrics… Lack of Cohesion in Methods (LCOM) Cohesion captures how close are different methods ofa class boundTwo methods form a cohesive pair if they access somecommon variablesForm a non-cohesive pair if no common variablesHigh cohesion is highly desirable LCOM is the number of method pairs that are non-cohesive minus the number of cohesive pairs Not significant in predicting fault tolerance of a class
  75. 75. OO Design 75Metrics Studies Show Weighted Methods per Class (WMC) Classes tend to have only small number of methodsClasses are simple and provide some specific abstraction andoperationsOnly few classes have many methods defined in them Has a reasonable correlation with fault-proneness of a class Depth of Inheritance (DIT) Classes tend to be close to the rootMax DIT around 10Most classes have DIT of 0 (they are the root) Designers tend to keep the number of abstraction levels small,i.e., they give up reusability in favor of comprehensibility Number of Children (NOC) Classes generally had a smaller NOC value with most having 0 Inheritance was not used very heavily
  76. 76. OO Design 76Metrics Studies Show… Coupling Between Classes (CBC) Most classes are self contained with CBC = 0Not coupled with any other class Interface objects tend to have higher CBC Response for a Class (RFC) Most classes tend to invoke a small number ofmethods of other classes Classes for interface objects tend to have higher RFC Lack of Cohesion in Methods (LCOM) Not very good at predicting fault-proneness
  77. 77. OO Design 77Summary OO is a newer paradigm, slowly replacing thefunctional approach OO models both data and functions UML is a notation that is used often to modelsystems in an OO manner UML provides various diagrams for modeling thestructure, dynamic behavior, etc. Through UML modeling, design for the systemcan be developed Metrics can help predict fault proneness of design
  78. 78. OO Design 78Example OO Design – PIMSPersonal Investment System Help investors keep track of theirinvestments Determine rate of return On individual investments On overall portfolio Determine net worth of portfolios
  79. 79. OO Design 79Example OO Design –PIMS… Investor can have many portfolios Portfolio can have many investments Investor can invest and withdraw any amount of money at any time Dates and amounts are tracked by PIMS Get current value of each investment from Web site Invest in instruments with fixed interest rates Alert to notify pending maturity dates Save information about the portfolio Edit entered data View any portfolio Summary Detailed Provide security Determine rate of return For each investment Overall for each portfolio Total investments Compute on monthly basis
  80. 80. OO Design 80Example OO Design – PIMS…Basic ClassesClass Principle ResponsibilityInvestment Manages computations regarding total investment.Portfolio Manages computations regarding a Portfolio.Security Manages computations related to a security.Transaction Manages computations and stores attributes related to a transaction.GUI Manages the Graphical User Interface.NetLoader Manages downloading current prices of shares from the Internet.Current ValueSystemManages current value of shares.Alerts Manages alerts.SecurityManager Manages user validation.DataRepository Manages all file operations. It is an interface between the mainmodules and the database (which in our case is done using filesystem.)
  81. 81. OO Design 81Example OO Design – PIMS…Inheritance StructureTwo kinds of securitiesBank: interest bearingShares: trading/dividendsTwo kinds of transactionsbuy: exchange cash for securitysell: exchange security for cash
  82. 82. OO Design 82Example OO Design – PIMS…Aggregation StructureAn investment consists of many portfoliosA portfolio can consist of many differentsecuritiesMany transactions can act on a singlesecurity
  83. 83. OO Design 83Example OO Design – PIMS…Class DiagramInvestmentPortfolioSecurityBank Deposit SharesTransactionDebit Credit1m1m1m
  84. 84. OO Design 84Example OO Design – PIMS…associations for action Create/Delete/Edit Transaction
  85. 85. OO Design 85Example OO Design – PIMS…Class diagram with all classes and associations
  86. 86. OO Design 86Example OO Design – PIMS…Basic ActionsActionsCreate/Delete/Rename Portfolio/Security.Create/Delete/Edit Transactions.Calculate Net Worth of Investment/Portfolio/ Security.Calculate Rate of Investment of a security.Load Current Prices from the Internet.Check/Set/Delete Alerts.Validate User.
  87. 87. OO Design 87Example OO Design – PIMS…Sequence diagram for principle action Create Portfolio
  88. 88. OO Design 88Example OO Design – PIMS…Sequence diagram for principle action Delete Transaction
  89. 89. OO Design 89Example OO Design – PIMS…Sequence diagram for action Compute Net Worth ofInvestment/Portfolio/Security
  90. 90. OO Design 90Example OO Design – PIMS…Sequence diagram for action Compute ROI
  91. 91. OO Design 91Example OO Design – PIMS…Sequence diagram for action Load current prices fromthe Internet
  92. 92. OO Design 92Example OO Design – PIMS…Sequence diagram for action Set/Check/Delete Alerts
  93. 93. OO Design 93Example OO Design – PIMS…Sequence diagram for action Validate User