Docstoc

A Case Study Point-of Sale

Document Sample
A Case Study Point-of Sale Powered By Docstoc
					                       Object-oriented Analysis and Design




              Chap 17
              GRASP:
Designing Objects with Responsibilities




Software Engineering                                         1
                              Object-oriented Analysis and Design


                   Introduction
   Since  the UML is simply a standard visual
    modelling language, knowing its details doesn't
    teach you how to think in objects…
   This chapter and the next present the heart of
    OOD : they explain fundamental skills in OOD
    and are therefore very important.
   We emphasise the design of the dynamic view of
    the software solution (via the interaction
    diagrams) rather than the static view of the
    software (i.e. the design class diagram).

Software Engineering                                                2
                                                 Object-oriented Analysis and Design


      Requirements Analysis Scenario
 The first two-day requirements workshop is     The chief architect and business
 finished.                                      agree to implement and test some
                                                scenarios of Process Sale in the
                                                first three-week timeboxed iteration.
 Three of the twenty use cases that are the     Other artifacts have been started:
 most architecturally significant and of high   Supplementary Specification,
 business value have been analyzed in detail,   Glossary, and Domain Model.
 including, of course, the Process Sale use
 case. UP iterative methods recommends,
 analyzing only 10%~20% of the
 requirements in detail before starting to
 program.
 Programming experiments have resolved the      The chief architect has drawn some
 show-stopper technical questions, such as      ideas for the large-scale logical
 whether a Java Swing UI will work on a         architecture, using UML package
 touch screen.                                  diagrams. This is part of the UP
                                                Design Model.
Software Engineering                                                                    3
                                  Object-oriented Analysis and Design


       Design in an iterative process
   We   assume that many activities have already
    taken place generating many useful artifacts
    prior to design:
      Vision;
      Supplementary Specification;
      Domain Model;
      Use Cases;
      System Sequence Diagrams;
      Operation Contracts;

     In an agile approach however, not all artifacts
       may be fully detailed while additional others
       may well be needed…
Software Engineering                                                    4
                               Object-oriented Analysis and Design


         Design in an iterative process
   It  would be a big mistake however to start
    designing if we are having problems creating the
    artifacts above :
     in particular if your contracts are poor, it is
       without doubt because you are on the wrong
       track … The level of quality of the contracts
       is a very good indicator of future success for
       the iteration and therefore the project …



Software Engineering                                                 5
                               Object-oriented Analysis and Design


       Design in an iterative process
   During     OOD, using the previously generated
    artifacts and via the UML, we explore visually
    the necessary relationships between the objects
    to fulfil the requirements
   We may only do so for the difficult parts of the
    design that we wish to explore before coding: for
    the obvious parts, coding can be started as soon
    as what we have to do has been agreed (e.g. as
    described in a contract and supported by the
    domain model):

Software Engineering                                                 6
                                  Object-oriented Analysis and Design


       Design in an iterative process
      We   may update previous artifacts or explore them
       further in case of problems;
      We     sketch both interaction diagrams and
       complementary class diagrams (dynamic and static
       modelling) applying general OO design patterns (aka
       principles);
      We may record our effort using a fully fledged UML
       modelling tool (but remembering that in an agile
       approach we build models primarily to understand
       and communicate not to document);
      We may intertwine coding half-days in between
       modelling half-days within a single iteration;
   We must remain agile (but honest with ourselves).

Software Engineering                                                    7
                              Object-oriented Analysis and Design


       Design in an iterative process
   Hence  what we will see now may only apply to
    the most difficult parts of the software (these
    tend to be front-loaded in an evolutionary
    project, so that more time may be spent on hard
    OOD in the first few iterations than in the
    subsequent ones were direct coding may be
    acceptable)




Software Engineering                                                8
                                                                                                      Object-oriented Analysis and Design


                  Inputs of Object Design
                                                                           Domain Model
                                                                                                                                    Sample UP Artifact
                                                Sale                1..*         Sales
          Business modeling                                 1
                                                                                LineItem                         ...
                                                                                                                                    Relationships
                                             date                                                          ...
                                             ...                               quantity


                                                          -
                                                       Use Case Model
                                                                  Process Sale                                                          Supplementary
                                             Process         use
                                              Sale                1. Customer
                                                             case arrives...
                                                                                                                                        specification
                                   Cashier                  names 2. ...
                Requirements                                      3. Cashier
                                                                  enters item                          Functional
                                                                          .
                                                                  identifier
                                    Use Case Diagram                   Use Case Text                   requirements that
                                                    ideas for               system                     must be realized                 Non-functional
   inspiration for name                             the post
                                                           -                events
                                                                                                       by the objects
   of some software                                 conditions
                                                                                          : System
                                                                                                                                        Requirements
   document object                         :
                                   Operation                : Cashier make                                  Glossary                    domain rules
                                             (…
                                     enterItem )
                                                    system          NewSale  ()
                                   Post conditions operations
                                        -       :                    enterItem
                                   -. . .                                      )
                                                                   (id, quantity                                       item details,
            starting events to     Operation Contracts          System Sequence Diagrams                               formats,
            design, and                                                                                                validation
            detailed post                                                      Design Model
                                                       : Register                                : ProductCatalog          : Sale
            condition to satisfy
                                           enterItem
                                              ,      )
                                       (itemIDquantity
                                                           d=getProductDescription(itemID)
                          Design
                                                                 addLineItem(d, quantity)

                                                    Register                                           ProductCatalog
                                              ...                                               ...
                                              makeNewSale()                *               1
                                              enterItem()                                       getProductDescription()
                                              ...                                               ...


Software Engineering                                                                                                                                     9
                                                   Object-oriented Analysis and Design


                Inputs of Object Design
use case text defines the visible behavior    The Supplementary Specification
that the software objects must ultimately     defines the non-functional goals, such as
support objects are designed to implement     internalization, our objects must satisfy.
the use cases. In the UP, this OO design is
called the use case realization.
The system sequence diagrams identify the     The Glossary clarifies details of
system operation messages, which are the      parameters or data coming in from the
starting messages on our interaction          UI layer, data being passed to the
diagrams of collaborating objects.            database, and detailed item-specific
                                              logic or validation requirements, such as
                                              the legal formats and validation for
                                              product universal product codes.
The operation contracts may complement        The Domain Model suggests some
the use case text to clarify what the         names and attributes of software domain
software objects must achieve in a system     objects in the domain layer of the
operation. The post-conditions define         software architecture.
detailed achievements.
Software Engineering                                                                       10
                              Object-oriented Analysis and Design


          Outputs of Object Design
   UML    interaction, class, and package diagrams
    for the difficult parts of the design that we
    wished to explore before coding
   UI sketches and prototypes
   database models with UML data modeling
    profile notation.
   report sketches and prototypes




Software Engineering                                                11
                                     Object-oriented Analysis and Design


        Responsibility-Driven Design
     Responsibility as contract or obligation of class .
        Doing responsibilities of an object
          doing something itself, such as creating an object
            or doing a calculation
          initiating action in other objects
          controlling and coordinating activities in other
            objects
        Knowing responsibilities of an object include:
          knowing about private encapsulated data
          knowing about related objects
          knowing about things it can derive or calculate

Software Engineering                                                       12
                             Object-oriented Analysis and Design


       Responsibility-Driven Design
   Responsibilities  are assigned to classes of
    objects during object design.
     a     Sale is responsible for creating
       SalesLineItems (doing)
     a Sale is responsible for knowing its total
       (knowing).
   A good way to design a solution in terms of
    collaborating objects is to think in terms of
    responsibilities


Software Engineering                                               13
                                     Object-oriented Analysis and Design


       Responsibility-Driven Design
   Assigning some responsibilities can be obvious, for
    example if the domain model Sale class has a time
    attribute, it is obvious that a Sale object should be
    responsible for knowing its time. (no need for OOD to
    find that out …)
   On the other hand some responsibilities may involve
    hundreds of objects and rely on hundred of methods…
       A responsibility is not the same thing as a method :
        methods fulfil responsibilities.
       Responsibilities are implemented by means of
        methods that either act alone or collaborate with other
        methods and objects.

Software Engineering                                                       14
                                          Object-oriented Analysis and Design


        Responsibility-Driven Design
     Responsibility Driven Design is a general metaphor for
      thinking about OO software design. Think of software
      objects as similar to people with responsibilities who
      collaborate with other people to get work done.
      Responsibility Driven Design leads to viewing an OO
      design as a community of collaborating responsible
      objects.
        We    use interaction diagram           to    illustrate     these
         collaborations between objects.
     Given a responsibility there are usually many potential
      solutions in terms of collaborating objects:
        Patterns   are there to guide us towards good solutions …

Software Engineering                                                            15
                                        Object-oriented Analysis and Design


        Responsibility-Driven Design
     Guideline: Domain objects illustrate the attributes and
      associations, relevant responsibilities related to
      "knowing."
        ifthe domain model Sale class has a time attribute, that a
         software Sale class knows its time.
     Big responsibilities take hundreds of classes and
      methods. Little responsibilities might take one method.
        the   responsibility to "provide access to relational
         databases" may involve two hundred classes and
         thousands of methods.
        the responsibility to "create a Sale" may involve only one
         method in one class.


Software Engineering                                                          16
                                                       Object-oriented Analysis and Design


        Responsibilities/GRASP/UML
   GRASP: General Responsibility Assignment Software Patterns
     A  Learning Aid for OO Design with Responsibilities
      Assigning responsibilities to objects.

   Drawing UML interaction                          diagrams         realized         these
    responsibilities to methods.
      Sale objects are given a responsibility to create Payments, which is
       invoked with a makePayment message and handled with a
       corresponding makePayment method.
                                            :Sale
              makePayment(cashTendered)
                                                    create(cashTendered)
                                                                            :Payment

      Abstract implies Sale objects have
      a responsibility to create Payments

Software Engineering                                                                           17
                               Object-oriented Analysis and Design


                       Patterns
  A     pattern is a named and well-known
    problem/solution pair that can be applied in new
    contexts, with advice on how to apply it in novel
    situations and discussion of its trade-offs,
    implementations, variations, and so forth:
     There are hundreds of OO design patterns,
       only a few are fundamentals;




Software Engineering                                                 18
                               Object-oriented Analysis and Design


                       Patterns
     Patterns  do not express new software
      engineering ideas : quite the opposite in fact.
      Patterns codifies good solutions to well-
      known recurring problems. In fact many
      OOD patterns originate from traditional non-
      OO software engineering;
     Patterns have names which allow easier
      communication: we can talk of the low-
      coupling pattern, or the controller
      pattern and everyone knows what is being
      talked about.
Software Engineering                                                 19
                                           Object-oriented Analysis and Design
  An example of a basic pattern :
   Pattern  Name:      Information Expert
   Problem:            What is a basic principle by which to assign
    responsibilities to objects?
   Solution:           Assign a responsibility to the class that has the
    information needed to fulfill it.
   this is a very basic pattern, and one of the most useful (even just
    asking ourselves the question „who should be responsible for
    doing/knowing so and so?‟ yields an obvious answer).

•A very well known design pattern book
by the “gang of four” (GoF) is “Design
patterns : elements of reusable object-oriented
software” by Erich Gamma, Richard Helm, Ralph
Johnson, John Vissides. Addison Wesley, 1995,
ISBN: 0201633612.


 Software Engineering                                                            20
                              Object-oriented Analysis and Design


                   The GRASP
   GRASP      stands for General Responsibility
    Assignment Software Patterns [Craig Larman];
    there are 9 such OOD patterns:
     Creator, Information Expert, Low coupling,
       Controller, High Cohesion, Polymorphism,
       Pure Fabrication, Indirection, Protected
       Variations;
   We now see the first 5 in more details, and we
    will apply them more systematically on our case
    studies in the next chapter. The remaining four
    patterns will be seen later.
Software Engineering                                                21
                       Object-oriented Analysis and Design




Software Engineering                                         22
                                 Object-oriented Analysis and Design


                       Creator
 Problem
   Who   should be responsible for creating a new
    instance of some class?
   Assigned well, the design can support low
    coupling, increased clarity, encapsulation, and
    reusability.




Software Engineering                                                   23
                                 Object-oriented Analysis and Design


                       Creator
 Solution
   Assign   class B the responsibility to create an
    instance of class A if one of these is true
      B "contains" or compositely aggregates A.
      B records A.
      B closely uses A.
      B has the initializing data for A that will be
       passed to A when it is created. Thus B is an
       Expert with respect to creating A.
   B is a creator of A objects

Software Engineering                                                   24
                                                    Object-oriented Analysis and Design


                                  Creator
     NextGen POS Example: who should be responsible for
      creating a SalesLineItem instance?
        By Creator, look for a class that aggregates, contains
         SalesLineItem instances.

               Sale
            time
               1
                       Contains

                   1..*
                                                     Product
               Sales   *                            Description
              LineItem            Described-by 1
                                                   description
            quantity                               price
                                                   itemID

Software Engineering                                                                      25
                                               Object-oriented Analysis and Design


                            Creator
     A Sale contains (aggregates) many SalesLineItem
      objects
        Creator pattern suggests that Sale is a good candidate
         to have the responsibility of creating SalesLineItem
         instances.
        This leads to the design of object interactions shown
        This assignment of responsibilities requires that a
         makeLineItem method be defined in Sale
      :Register                  :Sale

            makeLineItem(quantity)       Create(quantity)
                                                            :SalesLineItem




Software Engineering                                                                 26
                                         Object-oriented Analysis and Design


                           Creator
     Discussion
        Expert    pattern: Initializing data is passed in during
         creation via some kind of initialization method, such as a
         Java constructor that has parameters.
        assume that a Payment instance, when created, needs to be
         initialized with the Sale total. Since Sale knows the total,
         Sale is a candidate creator of the Payment.
     Contraindications
        creation  requires significant complexity, conditionally
         creating an instance from one of a family of similar classes
         based upon some external property value.
        Concrete Factory/Abstract Factory rather than use Creator.



Software Engineering                                                           27
                                            Object-oriented Analysis and Design


                             Creator
     Benefits
        Low    coupling is supported, which implies lower
         maintenance dependencies and higher opportunities for
         reuse.
            Coupling    is not increased because the created class is
             visible to the creator class, due to the existing associations.
     Related Patterns or Principles
        Low   Coupling
        Concrete Factory and Abstract Factory
        Whole-Part describes a pattern to define aggregate objects
         that support encapsulation of components.



Software Engineering                                                              28
                                     Object-oriented Analysis and Design


              Information Expert
   Problem
      What     is a general principle of assigning
       responsibilities to objects?
         A Design Model may define hundreds or
           thousands of software classes, and an application
           may require hundreds or thousands of
           responsibilities to be fulfilled.
   Solution
      Assign a responsibility to the information expert: the
       class that has the information necessary to fulfill the
       responsibility.


Software Engineering                                                       29
                                            Object-oriented Analysis and Design


                 Information Expert
   NextGEN POS Example: some class needs to know the
    grand total of all the SalesLineItem instances of a sale.
      Who   should be responsible for knowing that?
      Information Expert of the Domain Model : look for class
       that has the information needed to determine the total - Sale.
          give the responsibility of knowing its total - method getTotal.
      This approach supports low representational gap between
       software design of objects and the concepts of real domain.
                           Sale
                           time
                             1 Contains
                                                     Product
                             1..*
                                                     Description
                           Sales
                                    * Described-by 1 description
                           LineItem
                                                     price
                           quantity                  itemID
Software Engineering                                                              30
                                                       Object-oriented Analysis and Design


                    Information Expert
 To create the interaction diagrams in order to assign
  responsibilities to objects.
 Who should know the line item subtotal?
      The  SalesLineItem knows its quantity and its associated
       ProductDescription; therefore, by Expert, SalesLineItem
       should determine the subtotal.
      For interaction diagram, the Sale should send getSubtotal
       messages to each of the SalesLineItems and sum the results
                                               this notation will imply
                                               we are interacting over            Sale
              SalesLineItem                    all elements of a collection
 New method                                                                       time
              quantity                                                            ...
              getSubtotal()   t=getTotal            1..*          lineItems[i]:
                                           :Sale                                  getTotal()
                                                   st=getSubtotal SaleLineItem

Software Engineering                                                                           31
                                                             Object-oriented Analysis and Design


                          Information Expert
 To fulfill the responsibility of knowing its subtotal, a
  SalesLineItem has to know the product price.
 The ProductDescription is an information expert on
  answering its price;
 SalesLineItem sends a message asking for the product price


           t=getTotal                                           [
                                                        lineItemsi ] :
                          :Sale                                                        Product
                                   1*:st=getSubtotal    SalesLineItem
                                                                                       Description
                                              1.1:p=getPrice()
    Sale                                                                  New method   description
                        SalesLineItem                                                  price
    time                                                                               itemID
    ...                 quantity                         :Product
                                                         Description                   getPrice()
    getTotal()          getSubtotal()




Software Engineering                                                                                 32
                                          Object-oriented Analysis and Design


                   Information Expert
     To fulfill the responsibility of knowing and answering
      the sale's total.
         assign three responsibilities to three design classes of
          objects in the interaction diagram.
         summarize the methods in the method section of a
          class diagram.


             Design Class                          Responsibility
  Sale                          knows sale total
  SalesLineItem                 knows line item subtotal
  ProductDescription            knows product price



Software Engineering                                                            33
                                Object-oriented Analysis and Design


              Information Expert
 Discussion
    the fulfillment of a responsibility often requires
     information crossing different classes of objects.
       many "partial" information experts will
        collaborate in the task.
       the sales total problem required the
        collaboration of three classes of objects. they
        need to interact via messages to share the
        work.


Software Engineering                                                  34
                                Object-oriented Analysis and Design


              Information Expert
 Discussion
    "Do  It Myself" strategy.
       In the real world, a sale does not tell you its
        total; it is an inanimate thing.
       In object-oriented software, all software
        objects are alive, and they can take on
        responsibilities and do things related to the
        information they know.



Software Engineering                                                  35
                                Object-oriented Analysis and Design


              Information Expert
 Discussion
    In  a business, the chief financial officer should
     be responsible for creating a profit-and-loss
     statement.
       software objects collaborate because the
         information is spread around, so it is with
         people. The company's chief financial officer
         may ask accountants to generate reports on
         credits and debits.


Software Engineering                                                  36
                                    Object-oriented Analysis and Design


                Information Expert
   Contraindications
      Coupling, cohesion, and duplication problems.
        who should be responsible for saving a Sale in a
          database? Sale class.
        The Sale class must contain database handling, SQL
          and JDBC.
        Lower cohesion: The class no longer focuses on just
          the pure application logic of "being a sale.“.
        Increase coupling: The class must be coupled to the
          database/JDBC services of another subsystem, rather
          than being coupled to other objects in the domain
          layer.
        Similar database logic would be duplicated in many
          persistent classes.
Software Engineering                                                      37
                              Object-oriented Analysis and Design


             Information Expert
 Contraindications
   The above violate basic architectural principle
      design for a separation of major system
       concerns.
      Keep application logic in one place (domain
       software objects).
      keep database logic in another place



Software Engineering                                                38
                                Object-oriented Analysis and Design


             Information Expert
 Benefits
    Information    encapsulation is maintained since
     objects use their own information to fulfill tasks.
     This usually supports low coupling.
    Behavior is distributed across the classes that
     have the required information, encouraging
     more cohesive "lightweight" class definitions
     that are easier to understand and maintain.



Software Engineering                                                  39
                           Object-oriented Analysis and Design


             Information Expert
 Related Patterns or Principles
   Low Coupling
   High Cohesion
 Also Known As
   Place responsibilities with data, That which
    knows, Do It Myself, Put Services with the
    Attributes They Work On.




Software Engineering                                             40
                              Object-oriented Analysis and Design


                  Low Coupling
   Problem
     How    to support low dependency, low change
      impact, and increased reuse?
   Solution
     Assign a responsibility so that coupling
      remains low. Use this principle to evaluate
      alternatives.




Software Engineering                                                41
                                     Object-oriented Analysis and Design


                    Low Coupling
     Coupling
        a measure of how strongly one element is connected
         to, has knowledge of, or relies on other elements.
        An element with low coupling is not dependent on
         too many other classes, subsystems, systems.
        High coupling problems:
           Forced local changes because of changes in
             related classes.
           Harder to understand in isolation.
           Harder to reuse because its use requires the
             additional presence of the classes on which it is
             dependent.
Software Engineering                                                       42
                                    Object-oriented Analysis and Design


                   Low Coupling
   NextGen POS example
      To create a Payment instance and associate it with the
       Sale. What class should be responsible for this?
      Which design, based on assignment of responsibilities,
       supports Low Coupling?
      In both cases we assume the Sale must eventually be
       coupled to knowledge of a Payment.



        Register          Payment               Sale




Software Engineering                                                      43
                                              Object-oriented Analysis and Design


                      Low Coupling
 Design  1
    Since a Register "records" a Payment in the real-
     world domain, the Creator pattern suggests
     Register as a candidate for creating the Payment.
    The Register instance could then send an
     addPayment message to the Sale, passing along
     the new Payment as a parameter.
    Adds coupling of Register to Payment
         makePayment() :Register 1:create()          p:Payment

                                   2:addPayment(p)       :Sale

Software Engineering                                                                44
                                             Object-oriented Analysis and Design


                     Low Coupling
   Design 2
      the Sale does the creation of a Payment, does not
       increase the coupling.
      Purely from the point of view of coupling, prefer Design
       2 because it maintains overall lower coupling.
      In practice, the level of coupling alone can't be
       considered in isolation from other principles such as
       Expert and High Cohesion.
                                     1:makePayment()
         makePayment()   :Register                        :Sale

                                           1.1:create()

                                                       p:Payment

Software Engineering                                                               45
                                     Object-oriented Analysis and Design

                   Low Coupling
   Discussion
      Inobject-oriented languages such as C++, Java, and C#,
      common forms of coupling from TypeX to TypeY include:
        TypeX    has an attribute (data member or instance
         variable) that refers to a TypeY instance, or TypeY
         itself.
        A TypeX object calls on services of a TypeY object.
        TypeX has a method that references an instance of
         TypeY, or TypeY itself, by any means. These
         typically include a parameter or local variable of type
         TypeY, or the object returned from a message being
         an instance of TypeY.
        TypeX is a direct or indirect subclass of TypeY.
        TypeY is an interface, and TypeX implements that
         interface.
Software Engineering                                                       46
                                     Object-oriented Analysis and Design


                   Low Coupling
   Discussion
      A subclass is strongly coupled to its superclass.
         suppose objects must be stored persistently in a
          relational or object database.
         creating an abstract superclass called
          PersistentObject.
         Disadvantage: it highly couples domain objects to a
          particular technical service and mixes different
          architectural concerns.
         Advantage: automatic inheritance of persistence
          behavior.
      Classes that are inherently generic and high reuse should
       have low coupling.
Software Engineering                                                       47
                                 Object-oriented Analysis and Design


                 Low Coupling
 Contraindications:   High coupling to stable elements
   and to pervasive elements is seldom a problem.
    J2EE application can safely couple itself to the
     Java libraries (java.util..), because they are stable
     and widespread.




Software Engineering                                                   48
                               Object-oriented Analysis and Design


                  Low Coupling
 Focus  on the points of realistic high instability or
  evolution.
   the NextGen project, the different third-party tax
    calculators (with unique interfaces) need to be
    connected to the system. Designing for low
    coupling at this variation point is practical.
 Benefits
   not affected by changes in other components
   simple to understand in isolation
   convenient to reuse
 Related Patterns: Protected Variation
Software Engineering                                                 49
                                        Object-oriented Analysis and Design

                        Controller
   Problem
      What first object beyond the UI layer receives and coordinates
      ("controls") a system operation?
        A  controller is the first object beyond the UI layer
         that is responsible for receiving or handling a system
         operation message.
        System operations were first explored during the
         analysis of SSD. These are the major input events
         upon our system. e.g.,
           when a cashier using a POS terminal presses the
            "End Sale" button, he is generating a system event
            indicating "the sale has ended."
           when a writer using a word processor presses the
            "spell check" button, he is generating a system
            event indicating "perform a spell check."

Software Engineering                                                          50
                                       Object-oriented Analysis and Design

                        Controller
    Solution
       Assign the responsibility to a class
          Represents the overall "system“, a device that the
            software is running within, or a major subsystem.
            These are all variations of a facade controller.
          Represents a use case scenario within which the
            system event occurs, named <UseCaseName>
            Handler, <UseCaseName> Coordinator, or
            <UseCaseName> Session (use case or session
            controller).
              Use the same controller class for all system
               events in the same use case scenario.
          "window," "view," and "document" classes are not
            on this list. They typically receive these events and
            delegate them to a controller.

Software Engineering                                                         51
                                      Object-oriented Analysis and Design


                       Controller
     NextGen POS example
        Some   system operations shown.
        This model shows the system itself as a class (which is
         legal and sometimes useful when modeling).


                          System

                   endSale()
                   enterItem()
                   makeNewSale()
                   makePayment ()
                   ...


Software Engineering                                                        52
                                                                     Object-oriented Analysis and Design


                                           Controller
   During analysis, system operations may be assigned to the class
    System.
   During design, a controller class is assigned the responsibility for
    system operations


             presses button

 : Cashier
                                     actionPerformed(actionEvent)

                UI Layer      :SaleJFrame                                  system operation message



      enterItem(itemID, qty)                           Which class of object should be responsible for receiving
                                                       this System event message? It is sometimes called the
                Domain
                              Controller
                                 :                     controller or coordinator. It does not normally do the work,
                 Layer
                                                       but delegates it to other objects. The controller is a kind of
                                                       facade onto the domain layer from the interface layer

Software Engineering                                                                                                    53
                                          Object-oriented Analysis and Design


                          Controller
 Who should be the controller for system events such as
  enterItem and endSale?
 By the Controller pattern
     Represents   the overall "system," "root object," device, or
      subsystem.Register, POSSystem represents a receiver or
      handler of all system events of a use case scenario.
      ProcessSaleHandler, ProcessSaleSession
     the domain of POS, a Register (POS Terminal) is a
      specialized device with software running in it.
     The interaction diagrams:


                                            :Register
             enterItem(id, quantity)


              enterItem(id, quantity)   :ProcessSaleHandler

Software Engineering                                                            54
                                                                       Object-oriented Analysis and Design


                                              Controller
   During design, the system operations identified during
    system behavior analysis are assigned to one or more
    controller classes, such as Register

                                    System                          Register
                              endSale()                     ...
system operations             enterItem()                   endSale()
discovered during system
behavior analysis             makeNewSale()                 enterItem()             allocation of system
                              Makepayment()                 makeNewSale()           operations during design
                              makeNewReturn()               Makepayment()           using one façade controller
                              enterReturnItem()             makeNewReturn()
                                                            enterReturnItem()


          System
                                              ProcessSale         HandleReturns
          endSale()                             Handler             Handler
          enterItem()                                                                 allocation of system
          makeNewSale()                 ...                 ...                       operations during design
          Makepayment()                 endSale()           enterReturnItem()         using using several use case
          makeNewReturn()               enterItem()         makeNewReturn   ()        controllers
                                        makeNewSale()       ...
          enterReturnItem()             makePayment()


Software Engineering                                                                                                 55
                                   Object-oriented Analysis and Design


                       Controller
   Discussion
      This is a delegation pattern.
        The UI layer shouldn't contain application logic.
        UI layer objects must delegate work requests to
          domain layer.
        In the domain layer, the Controller pattern
          summarizes choices, make for the domain object
          delegate that receives the work requests.
        the controller is a kind of facade into the domain
          layer from the UI layer.



Software Engineering                                                     56
                                    Object-oriented Analysis and Design


                       Controller
   Discussion
      To use the same controller class for all the system
       events of one use case so that the controller can
       maintain information about the state of the use case.
         to identify out-of-sequence system events (a
          makePayment operation before an endSale
          operation).
         Different controllers may be used for different use
          cases.




Software Engineering                                                      57
                                Object-oriented Analysis and Design


                       Controller
  Discussion
    A  common defect in the design of controllers
     from over-assignment of responsibility.
       A controller suffers from bad/low
        cohesion, violating the principle of High
        Cohesion.
    Guideline: a controller should delegate to
     other objects the work that needs to be done; it
     coordinates or controls the activity. It does not
     do much work itself.

Software Engineering                                                  58
                               Object-oriented Analysis and Design


                       Controller
  Discussion
    Boundary     objects are abstractions of the
      interfaces, entity objects are the application-
      independent/persistent domain objects, and
      control objects are use case handlers as
      described in this Controller pattern.




Software Engineering                                                 59
                                Object-oriented Analysis and Design


                       Controller
   Discussion
     facade    controller representing the overall
       system, or a subsystem.
         to choose some class name over the other
          layers of the application and that provides
          the main point of service calls from the UI
          layer.
         The facade could be an abstraction of the
          overall physical unit, such as a Register; a
          class representing the entire software
          system, such as POSSystem.
Software Engineering                                                  60
                                Object-oriented Analysis and Design


                       Controller
   Discussion
     Facade    controllers are suitable when there are
       not "too many" system events, or when the UI
       cannot redirect system event messages to
       alternating controllers, such as in a message-
       processing system.




Software Engineering                                                  61
                                      Object-oriented Analysis and Design


                       Controller
     Web UIs and Server-Side Application of Controller
        Web-MVC, the "controller" is part of the UI layer
         and controls the UI interaction and page flow. The
         GRASP controller is part of the domain layer and
         controls the handling of the work request, essentially
         unaware of what UI technology is being used (e.g., a
         Web UI, a Swing UI).




Software Engineering                                                        62
                                       Object-oriented Analysis and Design


                        Controller
     Benefits
        Increased potential for reuse and pluggable interfaces
           Application logic is not handled/bound in the
             interface layer, it can be replaced with a different
             interface.
           Delegating a system operation responsibility to a
             controller supports the reuse of the logic in future
             applications.




Software Engineering                                                         63
                                      Object-oriented Analysis and Design


                        Controller
     Benefits
        Opportunity to reason about the state of the use case.
          To ensure that system operations occur in a legal
             sequence, or we want to be able to reason about
             the current state of activity and operations within
             the use case.
          E.g., to guarantee that the makePayment
             operation cannot occur until the endSale operation
             has occurred. To capture this state information
             somewhere; the controller is one reasonable
             choice.


Software Engineering                                                        64
                                         Object-oriented Analysis and Design


                         Controller
   Bloated Controllers: has low cohesion unfocused and
    handling too many areas of responsibility
      There is only a single controller class receiving all system
       events in the system, and there are many of them.
      The controller performs many of the tasks to fulfill the
       system event, without delegating the work.
      A controller has many attributes, and maintains
       significant information about the system, which should
       have been distributed to other objects, or it duplicates
       information found elsewhere.



Software Engineering                                                           65
                                      Object-oriented Analysis and Design


                        Controller
   The cures for a bloated controller
      Add more controllers. a system does not have to need
       only one. Instead of facade controllers, employ use case
       controllers.
         e.g., an application with many system events - an
           airline reservation system - contain controllers: Use
           case       controllers:     MakeReservationHandler,
           ManageSchedulesHandler, ManageFaresHandler
      Design the controller so that it primarily delegates the
       fulfillment of each system operation responsibility to
       other objects.


Software Engineering                                                        66
                                    Object-oriented Analysis and Design


                       Controller
   UI Layer Does Not Handle System Events
      Assume the NextGen application has a window that
       displays sale information and captures cashier
       operations.
      Using the Controller pattern illustrates an acceptable
       relationship between the JFrame and the controller and
       other objects in a portion of the POS system.
      SaleJFrame class, part of the UI layer delegates the
       enterItem request to the Register object.




Software Engineering                                                      67
                                                            Object-oriented Analysis and Design


                               Controller


              presses button

         Cashier
                                     actionPerformed(actionEvent)


           UI Layer            : SaleJFrame               system operation message


                                        1:enterItem(itemID, qty)


                                                   1.1:makeLineItem(itemID, qty)
         Domain Layer           : Register                                           :Sale

                                             controller



Software Engineering                                                                              68
                                     Object-oriented Analysis and Design


                       Controller
   If a UI layer object (SaleJFrame) handles a system operation
    that represents part of a business process, then business
    process logic would be contained in an interface object;
       the opportunity for reuse of the business logic then
        diminishes because of its coupling to a particular
        interface and application.




Software Engineering                                                       69
                                                     Object-oriented Analysis and Design


                               Controller

                                                                              X
              presses button

         Cashier
                                     actionPerformed(actionEvent)
                                                It is undesirable for an interface layer
           UI Layer                             object such as a window to get involved in
                               : SaleJFrame
                                                deciding how to handle domain process.
                                                Business logic is embedded in the
                                                Presentation layer, which is not useful


                                     1:makeLineItem(itemID, qty)
         Domain Layer                                                 :Sale

              SaleJFrame should not
              sending message


Software Engineering                                                                         70
                                       Object-oriented Analysis and Design


                       Controller
   Related Patterns
      Command: In a message-handling system, each message
       may be represented and handled by a separate Command
       object.
      Façade: A facade controller is a kind of Facade
       [GHJV95].
      Layers: This is a POSA pattern. Placing domain logic in
       the domain layer rather than the presentation layer is part
       of the Layers pattern.
      Pure Fabrication: This GRASP pattern is an arbitrary
       creation of the designer, not a software class whose
       name is inspired by the Domain Model. A use case
       controller is a kind of Pure Fabrication.

Software Engineering                                                         71
                                     Object-oriented Analysis and Design


                    High Cohesion
   Problem
      How to keep objects focused, understandable, and
       manageable, and as a side effect, support Low Coupling?
      Cohesion: a measure of how strongly related and focused
       the responsibilities of a class or subsystem are.
      Low cohesion class
         does many unrelated things or too much work.
         represent a very "large grain" of abstraction or have
           taken on responsibilities that should have been
           delegated to other objects
         hard to comprehend, reuse, maintain, delicate;
           constantly affected by change
Software Engineering                                                       72
                                      Object-oriented Analysis and Design


                    High Cohesion
   Solution
      Assign a responsibility so that cohesion remains high.
      Use this to evaluate alternatives.




Software Engineering                                                        73
                                    Object-oriented Analysis and Design


                   High Cohesion
    POS Example: Low Coupling pattern for High Cohesion.
       to create a (cash) Payment instance and associate it
        with the Sale. What class should be responsible for
        this?




Software Engineering                                                      74
                                              Object-oriented Analysis and Design


                         High Cohesion
   Design 1
      Since Register records a Payment in the real-world domain, the
       Creator pattern suggests Register for creating the Payment.
      The Register instance could send an addPayment message to
       the Sale, passing along the new Payment as a parameter
      To places the responsibility for making a payment in the
       Register.
   To continuous make the Register class responsible for doing
    most of the work related to more system operations
      it   will become increasingly with tasks and become incohesive.
                     : Register
     makePayment()                                                      : Sale
                                  Create()
                                              p: Payment
                              addPayment(p)


Software Engineering                                                                75
                                         Object-oriented Analysis and Design


                    High Cohesion
   The second design delegates the payment creation
    responsibility to the Sale supports higher cohesion in the
    Register.
      Since the second design supports both high cohesion and
       low coupling.
   In practice, the level of cohesion alone can't be considered
    in isolation from other responsibilities and other principles
    such as Expert and Low Coupling.

                    : Register          : Sale
       makePayment()                                        p: Payment
                            makePayment()
                                                 Create()



Software Engineering                                                           76
                                      Object-oriented Analysis and Design


                    High Cohesion
   Discussion
      Very low cohesion: A class is responsible for many
       things in very different functional areas.
         RDB-RPC-Interface class is completely responsible
           for interacting with relational databases and for
           handling remote procedure calls.
         The responsibilities should be split into a family of
           classes related to RDB access and a family related to
           RPC support.




Software Engineering                                                        77
                                      Object-oriented Analysis and Design


                    High Cohesion
   Discussion
      Low cohesion: A class has responsibility for a complex
       task in one functional area.
         RDBInterface class is completely responsible for
           interacting with relational databases.
         The methods of the class are all related, but hundreds
           or thousands of methods.
         The class should split into a family of lightweight
           classes sharing the work to provide RDB access.




Software Engineering                                                        78
                                     Object-oriented Analysis and Design


                   High Cohesion
   Discussion
      High cohesion: A class has moderate responsibilities in
       one functional area and collaborates with other classes
       to fulfill tasks.
         RDBInterface class is only partially responsible for
           interacting with relational databases.
         It interacts with a dozen other classes related to
           RDB access in order to retrieve and save objects.




Software Engineering                                                       79
                                        Object-oriented Analysis and Design


                     High Cohesion
   Discussion
      Moderate cohesion: A class has lightweight and sole
       responsibilities in a few different areas that are logically
       related to the class concept but not to each other.
         Company class is completely responsible for (1)
           knowing its employees and (2) knowing its financial
           information.
         These two areas are not strongly related to each
           other, although both are logically related to the
           concept of a company.
         The total number of public methods is small.

Software Engineering                                                          80
                                       Object-oriented Analysis and Design


                    High Cohesion
     Discussion
        High cohesion class has a relatively small number of
         methods, with highly related functionality, and does
         not do too much work. It collaborates with other
         objects to share the effort if the task is large.
        This principle is an evaluative principle evaluating all
         design decisions.
        Real world
           if a person takes on too many unrelated
             responsibilities, then the person is not effective.
           Managers have not learned how to delegate, they
             are ready to become "unglued."
Software Engineering                                                         81
                                    Object-oriented Analysis and Design


                   High Cohesion
     Modular Design Principle: a system has been
      decomposed into a set of cohesive and loosely coupled
      modules.




Software Engineering                                                      82
                                     Object-oriented Analysis and Design


                   High Cohesion
     Contraindications
        Case 1
          Only one or two SQL experts know how to best
            define and maintain SQL.
          Few OO programmers may have strong SQL
            skills.
          Suppose the SQL expert is not even a comfortable
            OO programmer.
          The software architect may decide to group all the
            SQL statements into one class, RDBOperations,
            so that it is easy for the SQL expert to work on
            the SQL in one location.
Software Engineering                                                       83
                                      Object-oriented Analysis and Design


                    High Cohesion
     Contraindications
        Case 2: Lower cohesion is with distributed server
         objects.
           Because of overhead and performance
            implications associated with remote objects and
            remote communication, it is sometimes desirable
            to create fewer and larger, less cohesive server
            objects that provide an interface for many
            operations.
           Instead of a remote object with three fine-grained
            operations setName, setSalary, and setHireDate,
            there is one remote operation, setData, which
            receives a set of data. This results in fewer remote
            calls and better performance.
Software Engineering                                                        84
                                      Object-oriented Analysis and Design


                    High Cohesion
     Benefits
        Clarity and ease of comprehension of the design is
         increased.
        Maintenance and enhancements are simplified.
        Low coupling is often supported.
        Reuse of fine-grained, highly related functionality is
         increased because a cohesive class can be used for a
         very specific purpose.




Software Engineering                                                        85

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:10
posted:9/30/2011
language:English
pages:85