SlideShare ist ein Scribd-Unternehmen logo
1 von 63
Downloaden Sie, um offline zu lesen
Object-Oriented Programming:
                Introduction to Analysis and Design




Zeegee Software Inc.
RELEASE
The author of these slides, Zeegee Software Inc., has provided these slides
for personal educational use only. Zeegee Software reserves all rights to
the contents of this document.
Under no circumstances may the contents of this document, in part or
whole, be presented in a public forum or excerpted for commercial use
without the express permission of Zeegee Software.
Under no circumstances may anyone cause this electronic file to be altered
or copied in a manner which omits, changes the text of, or obscures the
readability of these Terms and Conditions.
INTRODUCTION
            Object-oriented design (OOD) techniques allow
            developers to…
                 – Identify what classes a given application will need
                   (abstraction).
                 – Determine how to organize the classes in a class
                   hierarchy (also abstraction).
                 – Identify the instance variables and methods that
                   should be defined for the classes, and how instances of
                   those class interact (association).
                 – Evaluate the quot;goodnessquot; of a given design by its use
                   of inheritance, encapsulation, etc. (coupling and cohesion).

Copyright © 1996, 2000 Zeegee Software Inc.        09/22/06         Object-Oriented Programming 2-3
IDENTIFYING CLASSES
                                     AND OBJECTS
        • Association
        • Abstraction




Copyright © 1996, 2000 Zeegee Software Inc.   09/22/06   Object-Oriented Programming 2-4
Association

                                              What is association?
           • Just as inheritance links classes together, association
             links instances of classes together:
                    – An object of class A [is] an object of class B: inheritance.
                    – An object of class A [has-part, talks-to, contains] an
                      object of class B: association.
           • Commonly, a binary relationship between two classes.
           • Association determines:
                    – The instance variables of classes.
                    – The quot;contentsquot; of collection classes.


Copyright © 1996, 2000 Zeegee Software Inc.            09/22/06        Object-Oriented Programming 2-5
Association

            Choosing association vs. inheritance
                          Inheritance                                       Association
                                                                                       1
                  Library                      Truck                               1         Library

                                                                      Bookmobile
                                                                                   1
      more                   Bookmobile                       less                     1       Truck
   appropriate                                            appropriate



                                                                                       1
             Microphone                       Speaker                              1
                                                                                           Microphone

                                                                      Telephone
                                                                                   1
       less                    Telephone                     more                      1    Speaker
   appropriate                                            appropriate

Copyright © 1996, 2000 Zeegee Software Inc.                09/22/06                         Object-Oriented Programming 2-6
Association

                Who implements the association?
           Both objects, if each object must send many messages to the
           other:

          E-R diagram                         Class design                    Sample objects

                                                                                  Manager
      Employee               m
                                              Employee     manager                    manager
                                                                                      underlings

             is-a                manages


                             1
       Manager                                Manager      underlings
                                                                        Manager
                                                                                      Employee
                                                                         manager                    Employee
                                                                                        manager
                                                                         underlings                   manager




Copyright © 1996, 2000 Zeegee Software Inc.              09/22/06                                  Object-Oriented Programming 2-7
Association

                Who implements the association?
           Only one object, especially in the case of quot;part-ofquot; or quot;containsquot;
           relationships, when one object is much simpler than the
           other:
          E-R diagram                         Class design                    Sample objects

                                                                                  Manager
      Employee               m
                                              Employee     manager                    manager
                                                                                      underlings

             is-a                manages


                             1
       Manager                                Manager      underlings
                                                                        Manager
                                                                                      Employee
                                                                         manager                    Employee
                                                                         underlings     manager
                                                                                                      manager



Copyright © 1996, 2000 Zeegee Software Inc.              09/22/06                                  Object-Oriented Programming 2-8
Association

                 Who implements the association?
           Neither object, if the association is overly complex; e.g., if it
           implies the existence of other entities which would really be
           managing the association:
       E-R diagram                            Class design                Sample objects
                                                                                   Office
             Employee
             Employee                         Employee    office                    occupants

             1               m



              shares-office
                                               Office     occupants    Em ployee
                                                                                    Em ployee
                                                                        office                     Em ployee
                                                                                     office
                                                                                                     office

      Note that quot;shares-officequot;
         implies an entity,
              quot;officequot;

Copyright © 1996, 2000 Zeegee Software Inc.                 09/22/06                            Object-Oriented Programming 2-9
Abstraction

                                          What is abstraction?
           • One job of an OO developer is to take a problem
             domain, and from it deduce which classes will be needed,
             and what instance/variables go in each class.
           • Generally easy to identify the lowest-level classes, but
             we often want to make use of inheritance!
           • Abstraction is the technique of deciding…
                    – What classes do we need?
                    – How do we organize our class hierarchy?
                    – Which variables/methods do we put in the superclasses,
                      and which do we put in the subclasses?

Copyright © 1996, 2000 Zeegee Software Inc.        09/22/06       Object-Oriented Programming 2-10
Abstraction

                        Basic approach to abstraction
                             1 Take a collection of proposed     A       B           C
                                      classes.
                               Identify common attributes            B
                             2 (instance variables) and                            C
                                                                 A
                               behaviors (methods).
                               Remove the common
                             3 attributes and behaviors, and     A D B             C
                               put them in a new class.
                               New class is a base class which
                             4 contains the common                   D                  C

                               elements; derived classes
                                                                 A            B
                               contain what's left.

Copyright © 1996, 2000 Zeegee Software Inc.         09/22/06             Object-Oriented Programming 2-11
Abstraction

                                              By functionality...
          Shape                                                      Strategy:
            color               area() = Ø
                                                             We look at the messages
                                                             we want objects of each
          Rectangle                                          class to respond to, and
                                                             organize our class hierarchy
            top                area() =
            left                 (bottom-top) *              accordingly.
            bottom               (right-left)
            right
                                                             Emphasis is on the role the
                                                             object plays in the
          Square                                             problem domain.




Copyright © 1996, 2000 Zeegee Software Inc.            09/22/06                  Object-Oriented Programming 2-12
Abstraction

                                              By functionality...
                                                    Advantages              Disadvantages
                                                • Good selection of     • Structure of derived
                                                  methods for each        classes may be less
                                                  class (strong           than optimal.
                                                  functional cohesion).
     Shape                                                              • Derived classes may
      color          area() = Ø                 • Intuitive class         contain superfluous
                                                  hierarchy, tending to   attributes.
     Rectangle
                                                  reflect quot;reality.quot;
      top
      left
                    area() =
                      (bottom-top) *
                                                • Facilitates addition of
      bottom
      right
                      (right-left)                new subclasses after
                                                  initial design and
                                                  implementation.
     Square


Copyright © 1996, 2000 Zeegee Software Inc.                09/22/06               Object-Oriented Programming 2-13
Abstraction

                                              By structure...
          Shape                                                      Strategy:
            color               area() = Ø
                                                             We look at the attributes
                                                             we want objects of each
          Square                                             class have, and organize our
                                                             class hierarchy for
            top                area() =
            left                 (width * width)             efficiency.
            width



          Rectangle
            height             area() =
                                 (width * height)




Copyright © 1996, 2000 Zeegee Software Inc.            09/22/06                  Object-Oriented Programming 2-14
Abstraction

                                              By structure...
                                                  Advantages              Disadvantages
                                              • Efficient structure   • Class hierarchy
                                                thoroughout class       strongly driven by
                                                hierarchy               implementation of
                                                                        classes at all levels.
     Shape                                    • Useful for
      color           area() = Ø                applications with a   • Requires most/all
                                                large number of         classes to be known a
     Square                                     objects and tight       priori.
      top                                       space.
      left
                    area() =
                      (width * width)                                 • Very unintuitive
      width
                                                                        hierarchy
                                                                        organization.
     Rectangle
      height        area() =
                      (width * height)


Copyright © 1996, 2000 Zeegee Software Inc.              09/22/06                 Object-Oriented Programming 2-15
Abstraction

             By functionality and structure...
                      Shape                                                     Strategy:
                       color         area() = Ø
                                                                       A combination of the
                                                                       previous two: we look for
                                                                       intuitive class organization,
                      RectangularShape                                 but also try to model
                                    width() = Ø
                                    height() = Ø                       exactly the attributes
                                    area() = width()*height()          needed.


     Rectangle                                     Square
      top           width() = (right-left)         top     width() = side
      left          height() = (bot-top)           left    height() = side
      bot                                          side
      right


Copyright © 1996, 2000 Zeegee Software Inc.                 09/22/06                   Object-Oriented Programming 2-16
Abstraction

             By functionality and structure...
                                                                Advantages          Disadvantages
                                                          • Efficient structure   • More difficult to
                                                            and functionality.      design well.
                Shape                                     • Intuitive class       • Tends to add abstract
                 color     area() = Ø                       hierarchy.              classes to hierarchy.
                                                                                  • Overuse of
                RectangularShape                                                    abstracted methods
                           width() = Ø
                           height() = Ø
                                                                                    may sacrifice
                           area() = width()*height()                                performance.

    Rectangle                                 Square
    top        width() = (right-left)         top    width() = side
    left       height() = (bot-top)           left   height() = side
    bot                                       side
    right


Copyright © 1996, 2000 Zeegee Software Inc.                            09/22/06            Object-Oriented Programming 2-17
Abstraction

                                          Minimal or none...
                                                                              Strategy:
                                                                     Create as flat a class
                                                                     hierarchy as possible, and
                    Shape                                            minimize the number of
                      color        area() = Ø                        actual classes.

   Rectangle                                    Square
     top           area() =                     top      area() =
     left            (bot -top) *               left       (side * side)
     bot             (right -left)              side
     right




Copyright © 1996, 2000 Zeegee Software Inc.               09/22/06                      Object-Oriented Programming 2-18
Abstraction

                                          Minimal or none...
                                                       Advantages                   Disadvantages
                                                • Simplifies design.              • Fails to capitalize on
                                                                                    benefits of inheritance
                                                • Eliminates inheritance
                                                  of unwanted structure. • Introduces code
                                                                           redundancy.
                                                • Easier to debug.
                                                                         • Does not preserve
                                                                           quot;real-worldquot;
                  Shape                                                    relationships between
                  color      area() = Ø                                    classes.

     Rectangle                                Square
      top       area() =                      top    area() =
      left        (bot -top) *                left     (side * side)
      bot         (right -left)               side
      right


Copyright © 1996, 2000 Zeegee Software Inc.                            09/22/06              Object-Oriented Programming 2-19
Abstraction

                                               Don't overdo it!
                                                               Object

                                                              Collection

                                    OrderedCollection                            UnorderedCollection

                                   Tree              Array                 Set          Bag

                    Quadtree                  List                          Hashtable

                                  Stack          Queue



Copyright © 1996, 2000 Zeegee Software Inc.                     09/22/06                               Object-Oriented Programming 2-20
EXERCISE:
                                              Abstraction
           Construct a hierarchy for the following classes:
                      PNTs are image files which have a 2-dimensional array of 1-byte
                      pixels, and a color lookup table.

                      JPEGs are image files which have a 2-dimensional array of 3-byte
                      (RGB) pixels.

                      GIFs are image files which have a 2-dimensional array of 1-byte
                      pixels, and a color lookup table. One special color may be
                      designated the transparent color.

                      HTMLs are files of ASCII text, where certain markup sequences
                      denote headings, font, etc.

                      PICTs are image files which represent graphical objects as
                      combinations of rectangles, ellipses, lines, etc.


Copyright © 1996, 2000 Zeegee Software Inc.          09/22/06                       Object-Oriented Programming 2-21
EVALUATING
                                               A DESIGN
        • Coupling
        • Cohesion




Copyright © 1996, 2000 Zeegee Software Inc.       09/22/06   Object-Oriented Programming 2-22
Coupling

                                              What is coupling?
           • Coupling is a rough measure of how strongly two
             objects are related.
           • A high degree of coupling (also called strong
             coupling) between two classes is indicated if…
                    – Both classes depend on each other's internal
                      structure.
                    – The instances of both classes send many different
                      messages to each other.
                    – The messages passed between the two classes are
                      complex; e.g., certain messages must be sent in a
                      sequence, the messages take many parameters, etc.

Copyright © 1996, 2000 Zeegee Software Inc.          09/22/06        Object-Oriented Programming 2-23
Coupling

                                  Strong coupling, in short




Copyright © 1996, 2000 Zeegee Software Inc.    09/22/06   Object-Oriented Programming 2-24
Coupling

                                         The Law of Demeter
                     For loose coupling and modifiability, follow this rule...


                   A method of a class should not depend in
                 any way on the structure of any class, except
                                   its own.


                      In the weak form: direct access to the instance
                      variables of a superclass is allowed.

                      In the strong form: direct access to the instance
                      variables of a superclass is prohibited.
Copyright © 1996, 2000 Zeegee Software Inc.     09/22/06                  Object-Oriented Programming 2-25
Coupling

                                         The Law of Demeter
               The bottom line: inside a method, one may only
               access or send messages to the following objects:
                    – The quot;selfquot; object (the object actually executing the
                      method).
                    – Instance/class variables defined in the same class which
                      has defined the method being executed (not those
                      defined in its base classes!).
                    – Arguments of the method.
                    – Global variables.
                    – Local variables of the method.

Copyright © 1996, 2000 Zeegee Software Inc.     09/22/06             Object-Oriented Programming 2-26
Coupling

             Appropriate coupling in OO Design
           Strive for low message coupling:
                    – Reduce the number of messages passed between
                      objects.
                    – Simplify messages to a few parameters.
                    – Avoid requiring multi-message sequences.
         car.pushPedal(CLUTCH);
         car.shiftToGear(PARK);
         car.insertKey(carKey);                           car.start(carKey);
         car.pushPedal(GAS);
         car.turnKeyInIgnition();




Copyright © 1996, 2000 Zeegee Software Inc.    09/22/06                Object-Oriented Programming 2-27
Coupling

             Appropriate coupling in OO Design
            Strive for low association coupling:
                    – Reduce extent to which objects depend on the internal
                      structure of each other
                    – Reduce the use of superclass' instance variables by
                      subclasses (strong form of the Law of Demeter).
        class Person {
           String first, last;
           getName { first + last }
        }

        class Doctor : Person {                           class Doctor : Person {
           getName {                                         getName {
                     quot;Drquot; + first + last;                         quot;Drquot; + Person::getName();
                }                                             }
        }                                                 }

Copyright © 1996, 2000 Zeegee Software Inc.    09/22/06                        Object-Oriented Programming 2-28
Coupling

             Appropriate coupling in OO Design
            Strive for moderate inheritance coupling:
                    – Abstract so that subclasses depend on the methods (but
                      not the structure!) of their superclasses.
                    – Use or refine as many of superclass' operations as
                      possible in the child classes.
        class Person {
           hello {
                      print quot;Hi!quot;
               }
        }

        class Doctor : Person {                           class Doctor : Person {
           greetings {                                       greetings {
                       print quot;Hi!quot;;                               hello();
                }                                             }
        }                                                 }

Copyright © 1996, 2000 Zeegee Software Inc.    09/22/06                      Object-Oriented Programming 2-29
Cohesion

                                              What is cohesion?
           • Cohesion is a measure of how effectively a group of
             elements (i.e., instance variables, methods) models a
             concept (i.e., a class).
           • Basically... how well does your model quot;hold together?quot;
           • To measure it, we must know a few terms...




Copyright © 1996, 2000 Zeegee Software Inc.          09/22/06     Object-Oriented Programming 2-30
Cohesion

                                              Relevance
           • An element is relevant to an object if is directly
             associated with the object, instead of being associated
             through some chain of invisible objects.
            class Person {                                  class Person {
               String name;                                    String name;
               String automobileTag;                           Car automobile;
               String automobileYear;                       }
            }
                                                            class Car {
             Not relevant: people don't have                   String tag;
             automobile tags; automobiles                      int year;
                           do!.                             }


           • Be on the lookout for compound nouns (like
             automobileTag) ... they can indicate invisible objects!
Copyright © 1996, 2000 Zeegee Software Inc.      09/22/06                    Object-Oriented Programming 2-31
Cohesion

                                              Necessity
           • An element is necessary to an object if its presence is
             required for the accurate modelling of the object.
                                                            class TriagePatient {
      class TriagePatient {                                    Boolean inShock?
         Boolean inShock?                                      String bloodType;
         String bloodType;                                  }
         String favoriteTVshow;
      }                                                     class RecoveringPatient {
                                                               String favoriteTVshow;
              Not necessary: do we really                   }
             need to know their TV show?

           • Be on the lookout for attributes which are only used
             under certain rare conditions... maybe your objects
             should quot;evolvequot; from class to class, or maybe the
             attributes belong in a subclass.
Copyright © 1996, 2000 Zeegee Software Inc.      09/22/06                   Object-Oriented Programming 2-32
Cohesion

                                              Completeness
           • A model of a concept is complete if no necessary
             elements have been omitted:
      class Stack {                                           class Stack {
         int size;                                               int size;
         Object elems[];                                         Object elems[];

              push(elem) {...}                                    push(elem) {...}
      }                                                           pop() { }
                                                              }
             Not complete: I see push()...
                 but where's pop()?

           • IMHO it is okay to omit some relevant elements... the
             real world is often too complex to model in entirety;
             knowing what to leave out is part of abstraction.

Copyright © 1996, 2000 Zeegee Software Inc.        09/22/06                    Object-Oriented Programming 2-33
Cohesion

                                              Strong cohesion
           • Consider a class intended to model some real-world
             concept. Its elements are instance variables (which
             model structure) and methods (which model function).
           • A high degree of cohesion is indicated if…
                    – All the elements are relevant to the concept.
                    – All the elements are necessary to adequately model the
                      concept.
                    – No necessary elements are missing from the group; i.e.,
                      the group is complete.



Copyright © 1996, 2000 Zeegee Software Inc.         09/22/06          Object-Oriented Programming 2-34
Cohesion

             Appropriate cohesion in OO design
           • High cohesion is good! Strive for...
           • High structural cohesion: Every instance variable
             should be relevant to the object, necessary for the
             object's intended use, and the object's essence should be
             adequately captured by all provided instance variables.
           • High functional cohesion: Every method should be
             relevant to the object, necessary for the object's intended
             use, and the the provided methods should adequately
             embrace the behavior of the object.



Copyright © 1996, 2000 Zeegee Software Inc.     09/22/06      Object-Oriented Programming 2-35
APPROACHES TO
                                  APPLICATION DESIGN
           • Modelling external entities
           • Interface classes
           • Mix-ins
           • Abstract interfaces




Copyright © 1996, 2000 Zeegee Software Inc.   09/22/06   Object-Oriented Programming 2-36
Modelling external entities




     hasSaddle?                    climbOn()               hasSugar?   dumpInRiver()
     hasShoes?                       spur()                  weight    swatWithTail()
                                     feed()               likesToKick?
                                    groom()


Copyright © 1996, 2000 Zeegee Software Inc.    09/22/06                    Object-Oriented Programming 2-37
Interface classes

                             What are interface classes?
           • Just as encapsulation can help hide the quot;grottyquot; details of
             entities inside a program, so can it help simplify interaction
             with entities outside a program, when we provide intuitive
             quot;public interfacesquot; to…
                    – Other processes (clients, servers, children)
                    – Data files and databases
                    – Hardware devices (printers, displays, etc.)
                    – User interfaces
                    – Foreign code
           • Classes which represent external entities, and which exist
             for communicating with them, are called interface classes.

Copyright © 1996, 2000 Zeegee Software Inc.         09/22/06         Object-Oriented Programming 2-38
Interface classes

                          Client-server inteface classes
                      ExternalProcess                                     • Low-level interprocess
                                     send(buffer, nbytes)                   communicaton is done
                                     receive(buffer, nbytes)                inside the methods of the
                                                                            base classes.

                     InternetServer                                       • Methods and return values
                     socket         phoneUp(host, port)                     of the derived classes are
                                    hangUp()                                chosen to reflect server's
                                                                            actual quot;protocol.quot;

   HTTP Server                                     SMTP Server
                 get(URL, query)                           giveSender(name)
                 post(URL, query)                          giveRecipient(name)
                                                           giveMessage(text)



Copyright © 1996, 2000 Zeegee Software Inc.                    09/22/06                   Object-Oriented Programming 2-39
Interface classes

                          Sample SMTP interface class
           Here's a possible dialog with an interface class designed
           for sending mail to another user. The class' methods
           reflect the commands that are actually being sent to the
           SMTP (Simple Mail Transfer Protocol) server:

                 MailServer s;

                 s.phoneUp(quot;discovery.nasa.govquot;);
                 s.giveSender(quot;davebowmanquot;);
                 s.giveRecipient(quot;hal9000quot;);
                 s.giveMessage(quot;Open the pod bay door, HAL.quot;);
                 s.hangUp();


Copyright © 1996, 2000 Zeegee Software Inc.         09/22/06      Object-Oriented Programming 2-40
Interface classes

                         Interface classes for data files
           Most programs make extensive use of data files…
           encapsulating the internal structures of these files has the
           same benefits as encapsulating the implementation details
           of data structures:
                                              File


                        TextFile                             BinaryFile


                     ShellScript                     CDF              SFDU   FITS


                                              GeotailCDF


Copyright © 1996, 2000 Zeegee Software Inc.                09/22/06          Object-Oriented Programming 2-41
Interface classes

                Sample interfaces to data files
           CDF f;
                                                                            using
                                                                          generic
           f.open(quot;deathstar_blueprints.cdfquot;);                         superclass
             designer = f.getGlobalAttr(quot;DESIGNERquot;);
           f.close();

           BlueprintFile bf;
                                                                           using
                                                                  domain-specific
           bf.open(quot;deathstar_blueprints.cdfquot;);                         subclass
             designer = bf.getDesigner();
           bf.close();



Copyright © 1996, 2000 Zeegee Software Inc.         09/22/06           Object-Oriented Programming 2-42
Interface classes

              Sample interfaces to databases
          SybaseDatabase db;
          SybaseTable table;                                                using
                                                                          generic
          db.login(quot;skywalkerquot;, quot;darthBitesquot;);                         superclass
            db.newQuery();
            db.addToQuery(quot;select cblk from prisoners pquot;);
            db.addToQuery(quot;where p.name = 'Leia'quot;);
            table = db.doQuery();
            cellblock = table.row(1).field(1);
          db.logout();


         PrisonerDatabase db;
                                                                           using
         db.login(quot;skywalkerquot;, quot;darthBitesquot;);                     domain-specific
            cellblock = db.getCellBlock(quot;Leiaquot;);                        subclass
         db.logout();


Copyright © 1996, 2000 Zeegee Software Inc.         09/22/06           Object-Oriented Programming 2-43
Interface classes

                      Do we care how data is stored?
            Database db;
            Query    query;
            Results dbResults, totalResults;

            /* Build the query from current user input: */
            query = extractQuery(gUserInterface);

            /* Send query to all DBs, and pool results: */
            foreach db in gDatabases {
              dbResults = db.doQuery(query);
              totalResults.add(dbResults);
            }




Copyright © 1996, 2000 Zeegee Software Inc.         09/22/06      Object-Oriented Programming 2-44
Mix-ins

                                      The high/low conflict...
           • Two factors arise in creating an interface class to an
             external resource:
                    – We want the public interface of the class to reflect the
                      high-level attributes and behavior of the resource we're
                      modelling.
                    – We want to effectively utilize tools for interacting
                      with the resource at a low level, if they exist.
           • Now imagine a set of n different resources (e.g., image
             file formats), and a set of m problem domains, each of
             which wants to provide its own domain-specific interface
             to all n resources... ouch!

Copyright © 1996, 2000 Zeegee Software Inc.     09/22/06           Object-Oriented Programming 2-45
Mix-ins

                    Combinatorial code explosion...
           • Now imagine a set of n different resources (e.g., image
             file formats), and a set of m problem domains, each of
             which wants to provide its own domain-specific interface
             to all n resources... ouch!
 This team is developing
 a WWW browser: they                          Viewable           Viewable       Viewable        Viewable
  want a view() method.
                                                 GIF               JPEG           XBM              EPS
  This team is developing
 a graphics program: they
                                              Editable               Editable   Editable         Editable
   want editing methods                         GIF                   JPEG       XBM               EPS

 This team is developing                      Printable          Printable      Printable        Printable
  a printer driver: they                         GIF               JPEG           XBM               EPS
 want a bitmap() method

Copyright © 1996, 2000 Zeegee Software Inc.               09/22/06                          Object-Oriented Programming 2-46
Mix-ins

                                              Solution: mix-ins
           • If multiple-inheritance is supported, one solution is
             to develop general-purpose classes called mix-ins:
                    – The mix-in provides a generic (low-level) resource
                      interface.
                    – The application defines one abstract class which
                      defines the desired (high-level) domain-specific
                      interface.
                    – The application then defines one concrete subclass for
                      each type of resource, inheriting both from the
                      abstract class and the mix-in.
           • So: to add the desired low-level functionality to any
             class... just quot;mix inquot; the needed code via inheritance!
Copyright © 1996, 2000 Zeegee Software Inc.          09/22/06     Object-Oriented Programming 2-47
Mix-ins

                                         A sample application
        GIF and JPEG                                                                MyAppImage is our domain-
   are the mix-in classes                         Image                              specific class representing
   with low-level routines                                                          kinds of images we deal with


    GIF                                           JPEG                          MyAppImage
         getDataBlock(attrname)                      retrieveCmnt(number)          getAuthor() = Ø




                                              MyAppGIF                      MyAppJPEG
                                               getAuthor() = {               getAuthor() = {
                                                 getDataBlock(quot;AUTHquot;);         retrieveCmnt(2);
                                               }                             }




Copyright © 1996, 2000 Zeegee Software Inc.                    09/22/06                           Object-Oriented Programming 2-48
Abstract interfaces

                                              The scenario
           Suppose you are developing a graphics library which lets you
           output any raster (pixellated) image in PNG format. You are
           all set to define classes GIF, JPEG, etc., each of which has an
           writePNG() method, when you think...
                        Why should I force people to use my classes? Why not allow them
                        to provide their own? So long as they provide a few methods like
                        numRows(), numCols(), and getPixelColor(r,c), who cares
                        how they've implemented it?
           So you turn it around, and provide an writePNG() routine
           which implements the real guts... and all it demands is that
           the object you give it has a certain public interface.



Copyright © 1996, 2000 Zeegee Software Inc.          09/22/06               Object-Oriented Programming 2-49
Abstract interfaces

                              Yes, it's just encapsulation!
           • Just like encapsulation, but it's the class user who
             draws up the quot;public interface contractquot;... and would-be
             class developers must obey it!
                    – Contract might be drawn up before any real classes
                      which obey that contract have been built...
                    – Like inventing a phonograph, and telling people how to
                      make records that will play on it.
           • Good technique for providing reusable classes in a rich
             domain with many developers.
           • Existing, incompatible classes can often be retrofitted
             through subclasses that obey the needed interface.
Copyright © 1996, 2000 Zeegee Software Inc.          09/22/06       Object-Oriented Programming 2-50
Abstract interfaces

                       Abstract interfaces in practice
           • Some OO languages (Java) let you formally define an
             interface: it's simply a set of method declarations.
           • Some OO languages with run-time binding (Perl5) are
             informal: interface is just specified by documentation;
             up to class user to send in an appropriate object.
           • Abstract interfaces form the basis of tying in Perl...
             objects with the right methods can become the quot;back
             endquot; of built-in data types like arrays and hashes!




Copyright © 1996, 2000 Zeegee Software Inc.          09/22/06       Object-Oriented Programming 2-51
WHEN WORLDS COLLIDE:
                          OO IN NON-OO DOMAINS
           • Pseudoclasses
           • Wrapper classes




Copyright © 1996, 2000 Zeegee Software Inc.           09/22/06       Object-Oriented Programming 2-52
Pseudoclasses

            Using OOD in non-OO domains
           • Sometimes we don't have an OO programming language
             at our disposal, yet we recognize the strengths or
             relevance of an OO approach for a task.
           • Remember some of the principle goals of OO languages:
                    – Modifiability, for code designers.
                    – Understandability, for code users.
                    – Reusability, for code designers and users.




Copyright © 1996, 2000 Zeegee Software Inc.       09/22/06         Object-Oriented Programming 2-53
Pseudoclasses

                                  What are Pseudoclasses?
           • Developed as a coding strategy for the C programming
             language, which has no classes, encapsulation, etc.
             Inspired by C++.
           • Principle can be used in nearly any non-OO language.
           • quot;Classesquot; are ordinary typedef'd structs.
           • quot;Methodsquot; are functions tied to a pseudoclass by
             consistent use of a conventions for:
                    – Function naming.
                    – Argument ordering.
                    – Return value type and interpretation.
Copyright © 1996, 2000 Zeegee Software Inc.       09/22/06    Object-Oriented Programming 2-54
Pseudoclasses

                           Pseudoclass coding standard
       Classnames begin with capital letter...               Stack

       Method names have class signature as                  StackPush()
       prefix...                                             StackPop()

       Symbolic constants defined for return                 StackOK
       values, with class signature as prefix...             StackOVERFLOW
                                                             StackEMPTY

       First argument of method is always                    StackPush(Stack *this,
       pointer to object in question, and                              Elem elem);
       parameter is always named quot;thisquot;...                   StackPop(Stack *this);

       Always a set of constructor functions                 Stack *StackNew();
       for initiallizing a new object, and a                 StackFree(Stack *this);
       destructor for destroying any object...

Copyright © 1996, 2000 Zeegee Software Inc.       09/22/06                   Object-Oriented Programming 2-55
Pseudoclasses

                         A sample Pseudoclass header
              #define StackOK        0
              #define StackEMPTY    -1                                    Return values
              #define StackOVERFLOW -2

              typedef struct Stack {
                 int     numelems;
                 Pointer elems[MAXELEMS];
                                                                         Class definition
              } Stack;

              Stack *StackNew ();
              void   StackFree (Stack *this);                           Constructors and
                                                                          destructors
              int           StackPush (Stack *this, Elem elem);
              Elem          StackPop (Stack *this);
              int           StackSize ();                               Principle methods
              int           StackDo           (Stack *this,
                                               Func (*f)(Elem elem));
                                                                              Iterator

                                                Stack.h


Copyright © 1996, 2000 Zeegee Software Inc.                  09/22/06      Object-Oriented Programming 2-56
Wrapper classes

                                         The transition to OO
           • Problem: although you may have acquired an OO
             programming environment…
                    – We don't want to throw away or rewrite mountains
                      of existing, tested code in Fortran, C, assembly, etc.
                    – We may still need external non-OO libraries for
                      which source code is complex or unavailable (e.g., X
                      Widgets).
                    – Some non-OO code may run much faster than code
                      in our OO environment (e.g., C vs. Smalltalk).




Copyright © 1996, 2000 Zeegee Software Inc.        09/22/06       Object-Oriented Programming 2-57
Wrapper classes

                              What are wrapper classes?
           • Solution: Use wrapper classes. A wrapper class is a
             class where...
                    – The instance variables hold an externally defined data
                      structure.
                    – The methods are quot;prettyquot; front-ends to that data
                      structure's supporting functions.
           • The idea is that we provide developers with what looks
             like an object, but which in fact is just a thin front end
             onto non-OO routines.
           • A wrapper class is a special kind interface class...
             providing an encapsulated interface to foreign code!
Copyright © 1996, 2000 Zeegee Software Inc.        09/22/06         Object-Oriented Programming 2-58
Wrapper classes

                                          A C++ wrapper class
          #include quot;Int_Stack.hquot;

          class IntegerStack {

                 Int_Stack S;                                    Instance variable is
                                                                   the “wrapped”
                 int size() {                                       data structure
                    return s_numelems(&S);
                 }

                 void push(int elem) {
                    istack_push(elem, &S);                           Methods are
                 }                                              interfaces to functions
                                                                   operating on the
                 int pop() {                                        data structure
                    return pop_int_stack(&S);
                 }
          }



Copyright © 1996, 2000 Zeegee Software Inc.        09/22/06              Object-Oriented Programming 2-59
Wrapper classes

                                     Wrapping foreign code
     void email_file(char *eaddress,                            An external C routine which
                       char *sender,                            has been compiled and linked
                     char *filename);                           with a Smalltalk-like OOPL.

     method: Person                                             A method, defined for class
     email: filename from: sender                               Person in the OOPL. Takes a
                                                                file and another Person (the
          System                                                sender), and emails the file.
             callFunc: quot;email_filequot;
                                                                Real work done by sending a
             withArgs: [
                                                                message to the System object,
                (self getEmailAddress)                          telling it to call the installed
                (sender getName)                                function.
                filename
             ].                                                 Typically, only simple args
     %                                                          (ints, floats, strings) can be
                                                                passed.
Copyright © 1996, 2000 Zeegee Software Inc.        09/22/06                     Object-Oriented Programming 2-60
Wrapper classes

                              Wrapping and tying in Perl
     use GDBM_File;                                             Here is code using the
                                                                standard Perl5 wrapper class
     # Open database (tie to object):                           for accessing the GDBM
     tie %DB, 'GDBM_File',                                      libraries. And it allows you to
         quot;mydatafile.gdbquot;, 1;                                   use Perl's normal hash syntax!
                                                                In the Perl5 world, built-in
     # Read and write:
                                                                datatypes (like hashtables) may
     print quot;Id = quot;, $DB{'Id'}, quot;nquot;;                            be quot;tiedquot; to your own custom
     $DB{'Name'} = 'Janeway';                                   classes, as long as your classes
     $DB{'Rank'} = 'Captain';                                   provide the needed interface
                                                                methods.
     # Close database:
     untie %DB;                                                 In reality, each GDBM_File
                                                                object contains a number that
                                                                is really a struct pointer... this
                                                                number is passed in opaquely
                                                                to the libgdbm.a functions.

Copyright © 1996, 2000 Zeegee Software Inc.        09/22/06                     Object-Oriented Programming 2-61
Wrapper classes

                              Wrapping and tying in Perl
     package GDBM_File;                                          The trick was that the
                                                                 GDBM_File class provided all
     sub new { ... }                                             the special interface methods
     sub DESTROY { ... }                                         that tie() demands for tying
                                                                 objects to hashes... FETCH,
     sub        FETCH { ... }                 # key              STORE, etc.
     sub        STORE { ... }                 # key, val         That allowed tie() to make an
     sub        FIRSTKEY { ... }                                 ordinary hash variable, %DB,
     sub        NEXTKEY { ... }                                  into an interface to a GDBM
     sub        DELETE { ... }                # key              file... without requiring the
     sub        EXISTS { ... }                # key              user to learn new access
                                                                 methods!
                                                                 This is a wonderful example of
     # Really $x->STORE('Name', 'Kirk'):                         the power of encapsulation,
     $DB{'Name'} = 'Kirk';                                       polymorphism, and wrapping!


Copyright © 1996, 2000 Zeegee Software Inc.           09/22/06                 Object-Oriented Programming 2-62
PROJECT: MIME

           The story you are about to read is true. The assignment is
           do-able... in fact, your instructor has done it. :-)
           Your customer needs you to develop an email-handling
           system (a program that reads incoming mail, processes it, and
           maybe even replies to it).
           This is complicated by the fact that nowadays, people can
           send MIME mail with attachments, and any attachment can be
           in 1 of 5 different encodings. So you need to be able to parse
           multipart MIME messages... and maybe even generate them.
           Assume there is no software out there to do this in the
           language you're using.
           Now, design it.
Copyright © 1996, 2000 Zeegee Software Inc.        09/22/06   Object-Oriented Programming 2-63

Weitere ähnliche Inhalte

Was ist angesagt?

Jesse Robbins Keynote - Hacking Culture @ Cloud Expo Europe 2013
Jesse Robbins Keynote - Hacking Culture @ Cloud Expo Europe 2013Jesse Robbins Keynote - Hacking Culture @ Cloud Expo Europe 2013
Jesse Robbins Keynote - Hacking Culture @ Cloud Expo Europe 2013Jesse Robbins
 
LatJUG. Spring Roo
LatJUG. Spring RooLatJUG. Spring Roo
LatJUG. Spring Roodenis Udod
 
Graphicae Product Overview
Graphicae Product OverviewGraphicae Product Overview
Graphicae Product OverviewGraphicae
 
Agile Project Management and Scrum Introduction
Agile Project Management and Scrum IntroductionAgile Project Management and Scrum Introduction
Agile Project Management and Scrum IntroductionEric Krock
 
Cocoon Best Practises
Cocoon Best PractisesCocoon Best Practises
Cocoon Best Practisesmr.quinn
 
Introduction to OSLC
Introduction to OSLCIntroduction to OSLC
Introduction to OSLCopenservices
 
Simulation Professional - What each module can do for me
Simulation Professional - What each module can do for meSimulation Professional - What each module can do for me
Simulation Professional - What each module can do for mePrism Engineering, Inc.
 
Boeing Webinar - Integrating Quality in Portfolio Management - oct 2010
Boeing Webinar - Integrating Quality in Portfolio Management -  oct 2010Boeing Webinar - Integrating Quality in Portfolio Management -  oct 2010
Boeing Webinar - Integrating Quality in Portfolio Management - oct 2010Brent Barton
 
Sioux Hot-or-Not: Domain Driven Design (Edwin Van Dillen)
Sioux Hot-or-Not: Domain Driven Design (Edwin Van Dillen)Sioux Hot-or-Not: Domain Driven Design (Edwin Van Dillen)
Sioux Hot-or-Not: Domain Driven Design (Edwin Van Dillen)siouxhotornot
 
Enterprise IPv6 Deployment
Enterprise IPv6 Deployment Enterprise IPv6 Deployment
Enterprise IPv6 Deployment Cisco Canada
 
How to Design Frameworks
How to Design FrameworksHow to Design Frameworks
How to Design Frameworkselliando dias
 
Mastering Ejb4th Ed
Mastering Ejb4th EdMastering Ejb4th Ed
Mastering Ejb4th Edssiliveri
 
Continuous Deployment & Delivery + Culture Hacks @ QCON 2012
Continuous Deployment & Delivery + Culture Hacks @ QCON 2012Continuous Deployment & Delivery + Culture Hacks @ QCON 2012
Continuous Deployment & Delivery + Culture Hacks @ QCON 2012Jesse Robbins
 
Integrating Quality into Portfolio Management, PMI Silicon Valley Chapter Din...
Integrating Quality into Portfolio Management, PMI Silicon Valley Chapter Din...Integrating Quality into Portfolio Management, PMI Silicon Valley Chapter Din...
Integrating Quality into Portfolio Management, PMI Silicon Valley Chapter Din...Brent Barton
 
Agile Software Development In The Large
Agile Software Development In The LargeAgile Software Development In The Large
Agile Software Development In The LargeConSanFrancisco123
 
Selected Aspects of Software Development
Selected Aspects of Software DevelopmentSelected Aspects of Software Development
Selected Aspects of Software DevelopmentHaitham El-Ghareeb
 
Adobe Summit EMEA 2012 : 16706 Optimise Mobile Experience
Adobe Summit EMEA 2012 : 16706 Optimise Mobile ExperienceAdobe Summit EMEA 2012 : 16706 Optimise Mobile Experience
Adobe Summit EMEA 2012 : 16706 Optimise Mobile ExperienceBen Seymour
 
Java Optimization For Faster Code & Better Results | J Optimizer
Java Optimization For Faster Code & Better Results | J OptimizerJava Optimization For Faster Code & Better Results | J Optimizer
Java Optimization For Faster Code & Better Results | J OptimizerMichael Findling
 
February JUGL on Software Quality Analysis
February JUGL on Software Quality AnalysisFebruary JUGL on Software Quality Analysis
February JUGL on Software Quality Analysiscyrilpicat
 

Was ist angesagt? (20)

Jesse Robbins Keynote - Hacking Culture @ Cloud Expo Europe 2013
Jesse Robbins Keynote - Hacking Culture @ Cloud Expo Europe 2013Jesse Robbins Keynote - Hacking Culture @ Cloud Expo Europe 2013
Jesse Robbins Keynote - Hacking Culture @ Cloud Expo Europe 2013
 
LatJUG. Spring Roo
LatJUG. Spring RooLatJUG. Spring Roo
LatJUG. Spring Roo
 
Graphicae Product Overview
Graphicae Product OverviewGraphicae Product Overview
Graphicae Product Overview
 
Agile Project Management and Scrum Introduction
Agile Project Management and Scrum IntroductionAgile Project Management and Scrum Introduction
Agile Project Management and Scrum Introduction
 
Utah PMA Quarterly Meeting, June, 2009
Utah PMA Quarterly Meeting, June, 2009Utah PMA Quarterly Meeting, June, 2009
Utah PMA Quarterly Meeting, June, 2009
 
Cocoon Best Practises
Cocoon Best PractisesCocoon Best Practises
Cocoon Best Practises
 
Introduction to OSLC
Introduction to OSLCIntroduction to OSLC
Introduction to OSLC
 
Simulation Professional - What each module can do for me
Simulation Professional - What each module can do for meSimulation Professional - What each module can do for me
Simulation Professional - What each module can do for me
 
Boeing Webinar - Integrating Quality in Portfolio Management - oct 2010
Boeing Webinar - Integrating Quality in Portfolio Management -  oct 2010Boeing Webinar - Integrating Quality in Portfolio Management -  oct 2010
Boeing Webinar - Integrating Quality in Portfolio Management - oct 2010
 
Sioux Hot-or-Not: Domain Driven Design (Edwin Van Dillen)
Sioux Hot-or-Not: Domain Driven Design (Edwin Van Dillen)Sioux Hot-or-Not: Domain Driven Design (Edwin Van Dillen)
Sioux Hot-or-Not: Domain Driven Design (Edwin Van Dillen)
 
Enterprise IPv6 Deployment
Enterprise IPv6 Deployment Enterprise IPv6 Deployment
Enterprise IPv6 Deployment
 
How to Design Frameworks
How to Design FrameworksHow to Design Frameworks
How to Design Frameworks
 
Mastering Ejb4th Ed
Mastering Ejb4th EdMastering Ejb4th Ed
Mastering Ejb4th Ed
 
Continuous Deployment & Delivery + Culture Hacks @ QCON 2012
Continuous Deployment & Delivery + Culture Hacks @ QCON 2012Continuous Deployment & Delivery + Culture Hacks @ QCON 2012
Continuous Deployment & Delivery + Culture Hacks @ QCON 2012
 
Integrating Quality into Portfolio Management, PMI Silicon Valley Chapter Din...
Integrating Quality into Portfolio Management, PMI Silicon Valley Chapter Din...Integrating Quality into Portfolio Management, PMI Silicon Valley Chapter Din...
Integrating Quality into Portfolio Management, PMI Silicon Valley Chapter Din...
 
Agile Software Development In The Large
Agile Software Development In The LargeAgile Software Development In The Large
Agile Software Development In The Large
 
Selected Aspects of Software Development
Selected Aspects of Software DevelopmentSelected Aspects of Software Development
Selected Aspects of Software Development
 
Adobe Summit EMEA 2012 : 16706 Optimise Mobile Experience
Adobe Summit EMEA 2012 : 16706 Optimise Mobile ExperienceAdobe Summit EMEA 2012 : 16706 Optimise Mobile Experience
Adobe Summit EMEA 2012 : 16706 Optimise Mobile Experience
 
Java Optimization For Faster Code & Better Results | J Optimizer
Java Optimization For Faster Code & Better Results | J OptimizerJava Optimization For Faster Code & Better Results | J Optimizer
Java Optimization For Faster Code & Better Results | J Optimizer
 
February JUGL on Software Quality Analysis
February JUGL on Software Quality AnalysisFebruary JUGL on Software Quality Analysis
February JUGL on Software Quality Analysis
 

Andere mochten auch

ICSME14 - On the Impact of Refactoring Operations on Code Quality Metrics
ICSME14 - On the Impact of Refactoring Operations on Code Quality MetricsICSME14 - On the Impact of Refactoring Operations on Code Quality Metrics
ICSME14 - On the Impact of Refactoring Operations on Code Quality MetricsOscar Chaparro
 
Object Oriented Principles
Object Oriented PrinciplesObject Oriented Principles
Object Oriented PrinciplesEmprovise
 
A Validation of Object-Oriented Design Metrics as Quality Indicators
A Validation of Object-Oriented Design Metrics as Quality IndicatorsA Validation of Object-Oriented Design Metrics as Quality Indicators
A Validation of Object-Oriented Design Metrics as Quality Indicatorsvie_dels
 
Distributed & parallel system
Distributed & parallel systemDistributed & parallel system
Distributed & parallel systemManish Singh
 
Pressman ch-11-component-level-design
Pressman ch-11-component-level-designPressman ch-11-component-level-design
Pressman ch-11-component-level-designOliver Cheng
 
Metricas de software
Metricas de softwareMetricas de software
Metricas de softwaresophialara123
 
Chapter 6 software metrics
Chapter 6 software metricsChapter 6 software metrics
Chapter 6 software metricsdespicable me
 

Andere mochten auch (9)

ICSME14 - On the Impact of Refactoring Operations on Code Quality Metrics
ICSME14 - On the Impact of Refactoring Operations on Code Quality MetricsICSME14 - On the Impact of Refactoring Operations on Code Quality Metrics
ICSME14 - On the Impact of Refactoring Operations on Code Quality Metrics
 
Object Oriented Principles
Object Oriented PrinciplesObject Oriented Principles
Object Oriented Principles
 
A Validation of Object-Oriented Design Metrics as Quality Indicators
A Validation of Object-Oriented Design Metrics as Quality IndicatorsA Validation of Object-Oriented Design Metrics as Quality Indicators
A Validation of Object-Oriented Design Metrics as Quality Indicators
 
Sonar Metrics
Sonar MetricsSonar Metrics
Sonar Metrics
 
Distributed & parallel system
Distributed & parallel systemDistributed & parallel system
Distributed & parallel system
 
Pressman ch-11-component-level-design
Pressman ch-11-component-level-designPressman ch-11-component-level-design
Pressman ch-11-component-level-design
 
Metricas de software
Metricas de softwareMetricas de software
Metricas de software
 
Chapter 6 software metrics
Chapter 6 software metricsChapter 6 software metrics
Chapter 6 software metrics
 
Arquitectura
ArquitecturaArquitectura
Arquitectura
 

Ähnlich wie Oop 2

Timelessness of Lean Management
Timelessness of Lean ManagementTimelessness of Lean Management
Timelessness of Lean ManagementVersionOne
 
Complex Agile Backlog Management
Complex Agile Backlog ManagementComplex Agile Backlog Management
Complex Agile Backlog ManagementManageware
 
Migration Manager Workshop Leucir Marin Sep 2012
Migration Manager Workshop  Leucir Marin Sep 2012Migration Manager Workshop  Leucir Marin Sep 2012
Migration Manager Workshop Leucir Marin Sep 2012alipaiva
 
Managing product development flow across an IT organization
Managing product development flow across an IT organizationManaging product development flow across an IT organization
Managing product development flow across an IT organizationInstitut Lean France
 
What next in the agile world - Alan Shalloway
What next in the agile world - Alan ShallowayWhat next in the agile world - Alan Shalloway
What next in the agile world - Alan ShallowayAGILEMinds
 
42629 lecture 5 pt 1
42629 lecture 5 pt 142629 lecture 5 pt 1
42629 lecture 5 pt 1Tom Howard
 
IBM Collaborative Lifecycle Management
IBM Collaborative Lifecycle ManagementIBM Collaborative Lifecycle Management
IBM Collaborative Lifecycle ManagementAlan Kan
 
Sketching, Wireframing, Prototyping - How to Be Agile and Avoid Half-Baked Us...
Sketching, Wireframing, Prototyping - How to Be Agile and Avoid Half-Baked Us...Sketching, Wireframing, Prototyping - How to Be Agile and Avoid Half-Baked Us...
Sketching, Wireframing, Prototyping - How to Be Agile and Avoid Half-Baked Us...Philipp Schroeder
 
Microsoft EPM and Team Foundation Server [TFS]
Microsoft EPM and Team Foundation Server [TFS] Microsoft EPM and Team Foundation Server [TFS]
Microsoft EPM and Team Foundation Server [TFS] Jaiveer Singh
 
JP Morgan & Chase - OneBench IS Case
JP Morgan & Chase - OneBench IS CaseJP Morgan & Chase - OneBench IS Case
JP Morgan & Chase - OneBench IS CaseTiziano Tassi
 
Choosing the right Agile innovation practices: Scrum vs Kanban vs Lean Startu...
Choosing the right Agile innovation practices: Scrum vs Kanban vs Lean Startu...Choosing the right Agile innovation practices: Scrum vs Kanban vs Lean Startu...
Choosing the right Agile innovation practices: Scrum vs Kanban vs Lean Startu...JAX London
 
Beyond App Store - Distribution of iOS Applications
Beyond App Store - Distribution of iOS ApplicationsBeyond App Store - Distribution of iOS Applications
Beyond App Store - Distribution of iOS Applicationslet's dev GmbH & Co. KG
 
Employees as brand advocates in the social media sphere - Social Media Week C...
Employees as brand advocates in the social media sphere - Social Media Week C...Employees as brand advocates in the social media sphere - Social Media Week C...
Employees as brand advocates in the social media sphere - Social Media Week C...Kasper Risbjerg
 
Pojectmanagementver4
Pojectmanagementver4Pojectmanagementver4
Pojectmanagementver4sami325
 
The Human Side of Software Development
The Human Side of Software DevelopmentThe Human Side of Software Development
The Human Side of Software Developmentguy_davis
 
Estimation techniques and software metrics
Estimation techniques and software metricsEstimation techniques and software metrics
Estimation techniques and software metricsMae Abigail Banquil
 
Talent Base Case: Nokia.com Content Strategy
Talent Base Case: Nokia.com Content StrategyTalent Base Case: Nokia.com Content Strategy
Talent Base Case: Nokia.com Content StrategyLoihde Advisory
 
Invest In Smarter Collaboration Final V2
Invest In Smarter Collaboration Final V2Invest In Smarter Collaboration Final V2
Invest In Smarter Collaboration Final V2Neil Burston
 

Ähnlich wie Oop 2 (20)

Timelessness of Lean Management
Timelessness of Lean ManagementTimelessness of Lean Management
Timelessness of Lean Management
 
Complex Agile Backlog Management
Complex Agile Backlog ManagementComplex Agile Backlog Management
Complex Agile Backlog Management
 
Migration Manager Workshop Leucir Marin Sep 2012
Migration Manager Workshop  Leucir Marin Sep 2012Migration Manager Workshop  Leucir Marin Sep 2012
Migration Manager Workshop Leucir Marin Sep 2012
 
Managing product development flow across an IT organization
Managing product development flow across an IT organizationManaging product development flow across an IT organization
Managing product development flow across an IT organization
 
What next in the agile world - Alan Shalloway
What next in the agile world - Alan ShallowayWhat next in the agile world - Alan Shalloway
What next in the agile world - Alan Shalloway
 
42629 lecture 5 pt 1
42629 lecture 5 pt 142629 lecture 5 pt 1
42629 lecture 5 pt 1
 
IBM Collaborative Lifecycle Management
IBM Collaborative Lifecycle ManagementIBM Collaborative Lifecycle Management
IBM Collaborative Lifecycle Management
 
Sketching, Wireframing, Prototyping - How to Be Agile and Avoid Half-Baked Us...
Sketching, Wireframing, Prototyping - How to Be Agile and Avoid Half-Baked Us...Sketching, Wireframing, Prototyping - How to Be Agile and Avoid Half-Baked Us...
Sketching, Wireframing, Prototyping - How to Be Agile and Avoid Half-Baked Us...
 
Microsoft EPM and Team Foundation Server [TFS]
Microsoft EPM and Team Foundation Server [TFS] Microsoft EPM and Team Foundation Server [TFS]
Microsoft EPM and Team Foundation Server [TFS]
 
JP Morgan & Chase - OneBench IS Case
JP Morgan & Chase - OneBench IS CaseJP Morgan & Chase - OneBench IS Case
JP Morgan & Chase - OneBench IS Case
 
Choosing the right Agile innovation practices: Scrum vs Kanban vs Lean Startu...
Choosing the right Agile innovation practices: Scrum vs Kanban vs Lean Startu...Choosing the right Agile innovation practices: Scrum vs Kanban vs Lean Startu...
Choosing the right Agile innovation practices: Scrum vs Kanban vs Lean Startu...
 
Beyond App Store - Distribution of iOS Applications
Beyond App Store - Distribution of iOS ApplicationsBeyond App Store - Distribution of iOS Applications
Beyond App Store - Distribution of iOS Applications
 
MerlinUserGuide
MerlinUserGuideMerlinUserGuide
MerlinUserGuide
 
Employees as brand advocates in the social media sphere - Social Media Week C...
Employees as brand advocates in the social media sphere - Social Media Week C...Employees as brand advocates in the social media sphere - Social Media Week C...
Employees as brand advocates in the social media sphere - Social Media Week C...
 
Pojectmanagementver4
Pojectmanagementver4Pojectmanagementver4
Pojectmanagementver4
 
Envision Overview
Envision OverviewEnvision Overview
Envision Overview
 
The Human Side of Software Development
The Human Side of Software DevelopmentThe Human Side of Software Development
The Human Side of Software Development
 
Estimation techniques and software metrics
Estimation techniques and software metricsEstimation techniques and software metrics
Estimation techniques and software metrics
 
Talent Base Case: Nokia.com Content Strategy
Talent Base Case: Nokia.com Content StrategyTalent Base Case: Nokia.com Content Strategy
Talent Base Case: Nokia.com Content Strategy
 
Invest In Smarter Collaboration Final V2
Invest In Smarter Collaboration Final V2Invest In Smarter Collaboration Final V2
Invest In Smarter Collaboration Final V2
 

Kürzlich hochgeladen

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Kürzlich hochgeladen (20)

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

Oop 2

  • 1. Object-Oriented Programming: Introduction to Analysis and Design Zeegee Software Inc.
  • 2. RELEASE The author of these slides, Zeegee Software Inc., has provided these slides for personal educational use only. Zeegee Software reserves all rights to the contents of this document. Under no circumstances may the contents of this document, in part or whole, be presented in a public forum or excerpted for commercial use without the express permission of Zeegee Software. Under no circumstances may anyone cause this electronic file to be altered or copied in a manner which omits, changes the text of, or obscures the readability of these Terms and Conditions.
  • 3. INTRODUCTION Object-oriented design (OOD) techniques allow developers to… – Identify what classes a given application will need (abstraction). – Determine how to organize the classes in a class hierarchy (also abstraction). – Identify the instance variables and methods that should be defined for the classes, and how instances of those class interact (association). – Evaluate the quot;goodnessquot; of a given design by its use of inheritance, encapsulation, etc. (coupling and cohesion). Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-3
  • 4. IDENTIFYING CLASSES AND OBJECTS • Association • Abstraction Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-4
  • 5. Association What is association? • Just as inheritance links classes together, association links instances of classes together: – An object of class A [is] an object of class B: inheritance. – An object of class A [has-part, talks-to, contains] an object of class B: association. • Commonly, a binary relationship between two classes. • Association determines: – The instance variables of classes. – The quot;contentsquot; of collection classes. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-5
  • 6. Association Choosing association vs. inheritance Inheritance Association 1 Library Truck 1 Library Bookmobile 1 more Bookmobile less 1 Truck appropriate appropriate 1 Microphone Speaker 1 Microphone Telephone 1 less Telephone more 1 Speaker appropriate appropriate Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-6
  • 7. Association Who implements the association? Both objects, if each object must send many messages to the other: E-R diagram Class design Sample objects Manager Employee m Employee manager manager underlings is-a manages 1 Manager Manager underlings Manager Employee manager Employee manager underlings manager Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-7
  • 8. Association Who implements the association? Only one object, especially in the case of quot;part-ofquot; or quot;containsquot; relationships, when one object is much simpler than the other: E-R diagram Class design Sample objects Manager Employee m Employee manager manager underlings is-a manages 1 Manager Manager underlings Manager Employee manager Employee underlings manager manager Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-8
  • 9. Association Who implements the association? Neither object, if the association is overly complex; e.g., if it implies the existence of other entities which would really be managing the association: E-R diagram Class design Sample objects Office Employee Employee Employee office occupants 1 m shares-office Office occupants Em ployee Em ployee office Em ployee office office Note that quot;shares-officequot; implies an entity, quot;officequot; Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-9
  • 10. Abstraction What is abstraction? • One job of an OO developer is to take a problem domain, and from it deduce which classes will be needed, and what instance/variables go in each class. • Generally easy to identify the lowest-level classes, but we often want to make use of inheritance! • Abstraction is the technique of deciding… – What classes do we need? – How do we organize our class hierarchy? – Which variables/methods do we put in the superclasses, and which do we put in the subclasses? Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-10
  • 11. Abstraction Basic approach to abstraction 1 Take a collection of proposed A B C classes. Identify common attributes B 2 (instance variables) and C A behaviors (methods). Remove the common 3 attributes and behaviors, and A D B C put them in a new class. New class is a base class which 4 contains the common D C elements; derived classes A B contain what's left. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-11
  • 12. Abstraction By functionality... Shape Strategy: color area() = Ø We look at the messages we want objects of each Rectangle class to respond to, and organize our class hierarchy top area() = left (bottom-top) * accordingly. bottom (right-left) right Emphasis is on the role the object plays in the Square problem domain. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-12
  • 13. Abstraction By functionality... Advantages Disadvantages • Good selection of • Structure of derived methods for each classes may be less class (strong than optimal. functional cohesion). Shape • Derived classes may color area() = Ø • Intuitive class contain superfluous hierarchy, tending to attributes. Rectangle reflect quot;reality.quot; top left area() = (bottom-top) * • Facilitates addition of bottom right (right-left) new subclasses after initial design and implementation. Square Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-13
  • 14. Abstraction By structure... Shape Strategy: color area() = Ø We look at the attributes we want objects of each Square class have, and organize our class hierarchy for top area() = left (width * width) efficiency. width Rectangle height area() = (width * height) Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-14
  • 15. Abstraction By structure... Advantages Disadvantages • Efficient structure • Class hierarchy thoroughout class strongly driven by hierarchy implementation of classes at all levels. Shape • Useful for color area() = Ø applications with a • Requires most/all large number of classes to be known a Square objects and tight priori. top space. left area() = (width * width) • Very unintuitive width hierarchy organization. Rectangle height area() = (width * height) Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-15
  • 16. Abstraction By functionality and structure... Shape Strategy: color area() = Ø A combination of the previous two: we look for intuitive class organization, RectangularShape but also try to model width() = Ø height() = Ø exactly the attributes area() = width()*height() needed. Rectangle Square top width() = (right-left) top width() = side left height() = (bot-top) left height() = side bot side right Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-16
  • 17. Abstraction By functionality and structure... Advantages Disadvantages • Efficient structure • More difficult to and functionality. design well. Shape • Intuitive class • Tends to add abstract color area() = Ø hierarchy. classes to hierarchy. • Overuse of RectangularShape abstracted methods width() = Ø height() = Ø may sacrifice area() = width()*height() performance. Rectangle Square top width() = (right-left) top width() = side left height() = (bot-top) left height() = side bot side right Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-17
  • 18. Abstraction Minimal or none... Strategy: Create as flat a class hierarchy as possible, and Shape minimize the number of color area() = Ø actual classes. Rectangle Square top area() = top area() = left (bot -top) * left (side * side) bot (right -left) side right Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-18
  • 19. Abstraction Minimal or none... Advantages Disadvantages • Simplifies design. • Fails to capitalize on benefits of inheritance • Eliminates inheritance of unwanted structure. • Introduces code redundancy. • Easier to debug. • Does not preserve quot;real-worldquot; Shape relationships between color area() = Ø classes. Rectangle Square top area() = top area() = left (bot -top) * left (side * side) bot (right -left) side right Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-19
  • 20. Abstraction Don't overdo it! Object Collection OrderedCollection UnorderedCollection Tree Array Set Bag Quadtree List Hashtable Stack Queue Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-20
  • 21. EXERCISE: Abstraction Construct a hierarchy for the following classes: PNTs are image files which have a 2-dimensional array of 1-byte pixels, and a color lookup table. JPEGs are image files which have a 2-dimensional array of 3-byte (RGB) pixels. GIFs are image files which have a 2-dimensional array of 1-byte pixels, and a color lookup table. One special color may be designated the transparent color. HTMLs are files of ASCII text, where certain markup sequences denote headings, font, etc. PICTs are image files which represent graphical objects as combinations of rectangles, ellipses, lines, etc. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-21
  • 22. EVALUATING A DESIGN • Coupling • Cohesion Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-22
  • 23. Coupling What is coupling? • Coupling is a rough measure of how strongly two objects are related. • A high degree of coupling (also called strong coupling) between two classes is indicated if… – Both classes depend on each other's internal structure. – The instances of both classes send many different messages to each other. – The messages passed between the two classes are complex; e.g., certain messages must be sent in a sequence, the messages take many parameters, etc. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-23
  • 24. Coupling Strong coupling, in short Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-24
  • 25. Coupling The Law of Demeter For loose coupling and modifiability, follow this rule... A method of a class should not depend in any way on the structure of any class, except its own. In the weak form: direct access to the instance variables of a superclass is allowed. In the strong form: direct access to the instance variables of a superclass is prohibited. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-25
  • 26. Coupling The Law of Demeter The bottom line: inside a method, one may only access or send messages to the following objects: – The quot;selfquot; object (the object actually executing the method). – Instance/class variables defined in the same class which has defined the method being executed (not those defined in its base classes!). – Arguments of the method. – Global variables. – Local variables of the method. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-26
  • 27. Coupling Appropriate coupling in OO Design Strive for low message coupling: – Reduce the number of messages passed between objects. – Simplify messages to a few parameters. – Avoid requiring multi-message sequences. car.pushPedal(CLUTCH); car.shiftToGear(PARK); car.insertKey(carKey); car.start(carKey); car.pushPedal(GAS); car.turnKeyInIgnition(); Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-27
  • 28. Coupling Appropriate coupling in OO Design Strive for low association coupling: – Reduce extent to which objects depend on the internal structure of each other – Reduce the use of superclass' instance variables by subclasses (strong form of the Law of Demeter). class Person { String first, last; getName { first + last } } class Doctor : Person { class Doctor : Person { getName { getName { quot;Drquot; + first + last; quot;Drquot; + Person::getName(); } } } } Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-28
  • 29. Coupling Appropriate coupling in OO Design Strive for moderate inheritance coupling: – Abstract so that subclasses depend on the methods (but not the structure!) of their superclasses. – Use or refine as many of superclass' operations as possible in the child classes. class Person { hello { print quot;Hi!quot; } } class Doctor : Person { class Doctor : Person { greetings { greetings { print quot;Hi!quot;; hello(); } } } } Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-29
  • 30. Cohesion What is cohesion? • Cohesion is a measure of how effectively a group of elements (i.e., instance variables, methods) models a concept (i.e., a class). • Basically... how well does your model quot;hold together?quot; • To measure it, we must know a few terms... Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-30
  • 31. Cohesion Relevance • An element is relevant to an object if is directly associated with the object, instead of being associated through some chain of invisible objects. class Person { class Person { String name; String name; String automobileTag; Car automobile; String automobileYear; } } class Car { Not relevant: people don't have String tag; automobile tags; automobiles int year; do!. } • Be on the lookout for compound nouns (like automobileTag) ... they can indicate invisible objects! Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-31
  • 32. Cohesion Necessity • An element is necessary to an object if its presence is required for the accurate modelling of the object. class TriagePatient { class TriagePatient { Boolean inShock? Boolean inShock? String bloodType; String bloodType; } String favoriteTVshow; } class RecoveringPatient { String favoriteTVshow; Not necessary: do we really } need to know their TV show? • Be on the lookout for attributes which are only used under certain rare conditions... maybe your objects should quot;evolvequot; from class to class, or maybe the attributes belong in a subclass. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-32
  • 33. Cohesion Completeness • A model of a concept is complete if no necessary elements have been omitted: class Stack { class Stack { int size; int size; Object elems[]; Object elems[]; push(elem) {...} push(elem) {...} } pop() { } } Not complete: I see push()... but where's pop()? • IMHO it is okay to omit some relevant elements... the real world is often too complex to model in entirety; knowing what to leave out is part of abstraction. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-33
  • 34. Cohesion Strong cohesion • Consider a class intended to model some real-world concept. Its elements are instance variables (which model structure) and methods (which model function). • A high degree of cohesion is indicated if… – All the elements are relevant to the concept. – All the elements are necessary to adequately model the concept. – No necessary elements are missing from the group; i.e., the group is complete. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-34
  • 35. Cohesion Appropriate cohesion in OO design • High cohesion is good! Strive for... • High structural cohesion: Every instance variable should be relevant to the object, necessary for the object's intended use, and the object's essence should be adequately captured by all provided instance variables. • High functional cohesion: Every method should be relevant to the object, necessary for the object's intended use, and the the provided methods should adequately embrace the behavior of the object. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-35
  • 36. APPROACHES TO APPLICATION DESIGN • Modelling external entities • Interface classes • Mix-ins • Abstract interfaces Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-36
  • 37. Modelling external entities hasSaddle? climbOn() hasSugar? dumpInRiver() hasShoes? spur() weight swatWithTail() feed() likesToKick? groom() Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-37
  • 38. Interface classes What are interface classes? • Just as encapsulation can help hide the quot;grottyquot; details of entities inside a program, so can it help simplify interaction with entities outside a program, when we provide intuitive quot;public interfacesquot; to… – Other processes (clients, servers, children) – Data files and databases – Hardware devices (printers, displays, etc.) – User interfaces – Foreign code • Classes which represent external entities, and which exist for communicating with them, are called interface classes. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-38
  • 39. Interface classes Client-server inteface classes ExternalProcess • Low-level interprocess send(buffer, nbytes) communicaton is done receive(buffer, nbytes) inside the methods of the base classes. InternetServer • Methods and return values socket phoneUp(host, port) of the derived classes are hangUp() chosen to reflect server's actual quot;protocol.quot; HTTP Server SMTP Server get(URL, query) giveSender(name) post(URL, query) giveRecipient(name) giveMessage(text) Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-39
  • 40. Interface classes Sample SMTP interface class Here's a possible dialog with an interface class designed for sending mail to another user. The class' methods reflect the commands that are actually being sent to the SMTP (Simple Mail Transfer Protocol) server: MailServer s; s.phoneUp(quot;discovery.nasa.govquot;); s.giveSender(quot;davebowmanquot;); s.giveRecipient(quot;hal9000quot;); s.giveMessage(quot;Open the pod bay door, HAL.quot;); s.hangUp(); Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-40
  • 41. Interface classes Interface classes for data files Most programs make extensive use of data files… encapsulating the internal structures of these files has the same benefits as encapsulating the implementation details of data structures: File TextFile BinaryFile ShellScript CDF SFDU FITS GeotailCDF Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-41
  • 42. Interface classes Sample interfaces to data files CDF f; using generic f.open(quot;deathstar_blueprints.cdfquot;); superclass designer = f.getGlobalAttr(quot;DESIGNERquot;); f.close(); BlueprintFile bf; using domain-specific bf.open(quot;deathstar_blueprints.cdfquot;); subclass designer = bf.getDesigner(); bf.close(); Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-42
  • 43. Interface classes Sample interfaces to databases SybaseDatabase db; SybaseTable table; using generic db.login(quot;skywalkerquot;, quot;darthBitesquot;); superclass db.newQuery(); db.addToQuery(quot;select cblk from prisoners pquot;); db.addToQuery(quot;where p.name = 'Leia'quot;); table = db.doQuery(); cellblock = table.row(1).field(1); db.logout(); PrisonerDatabase db; using db.login(quot;skywalkerquot;, quot;darthBitesquot;); domain-specific cellblock = db.getCellBlock(quot;Leiaquot;); subclass db.logout(); Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-43
  • 44. Interface classes Do we care how data is stored? Database db; Query query; Results dbResults, totalResults; /* Build the query from current user input: */ query = extractQuery(gUserInterface); /* Send query to all DBs, and pool results: */ foreach db in gDatabases { dbResults = db.doQuery(query); totalResults.add(dbResults); } Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-44
  • 45. Mix-ins The high/low conflict... • Two factors arise in creating an interface class to an external resource: – We want the public interface of the class to reflect the high-level attributes and behavior of the resource we're modelling. – We want to effectively utilize tools for interacting with the resource at a low level, if they exist. • Now imagine a set of n different resources (e.g., image file formats), and a set of m problem domains, each of which wants to provide its own domain-specific interface to all n resources... ouch! Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-45
  • 46. Mix-ins Combinatorial code explosion... • Now imagine a set of n different resources (e.g., image file formats), and a set of m problem domains, each of which wants to provide its own domain-specific interface to all n resources... ouch! This team is developing a WWW browser: they Viewable Viewable Viewable Viewable want a view() method. GIF JPEG XBM EPS This team is developing a graphics program: they Editable Editable Editable Editable want editing methods GIF JPEG XBM EPS This team is developing Printable Printable Printable Printable a printer driver: they GIF JPEG XBM EPS want a bitmap() method Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-46
  • 47. Mix-ins Solution: mix-ins • If multiple-inheritance is supported, one solution is to develop general-purpose classes called mix-ins: – The mix-in provides a generic (low-level) resource interface. – The application defines one abstract class which defines the desired (high-level) domain-specific interface. – The application then defines one concrete subclass for each type of resource, inheriting both from the abstract class and the mix-in. • So: to add the desired low-level functionality to any class... just quot;mix inquot; the needed code via inheritance! Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-47
  • 48. Mix-ins A sample application GIF and JPEG MyAppImage is our domain- are the mix-in classes Image specific class representing with low-level routines kinds of images we deal with GIF JPEG MyAppImage getDataBlock(attrname) retrieveCmnt(number) getAuthor() = Ø MyAppGIF MyAppJPEG getAuthor() = { getAuthor() = { getDataBlock(quot;AUTHquot;); retrieveCmnt(2); } } Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-48
  • 49. Abstract interfaces The scenario Suppose you are developing a graphics library which lets you output any raster (pixellated) image in PNG format. You are all set to define classes GIF, JPEG, etc., each of which has an writePNG() method, when you think... Why should I force people to use my classes? Why not allow them to provide their own? So long as they provide a few methods like numRows(), numCols(), and getPixelColor(r,c), who cares how they've implemented it? So you turn it around, and provide an writePNG() routine which implements the real guts... and all it demands is that the object you give it has a certain public interface. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-49
  • 50. Abstract interfaces Yes, it's just encapsulation! • Just like encapsulation, but it's the class user who draws up the quot;public interface contractquot;... and would-be class developers must obey it! – Contract might be drawn up before any real classes which obey that contract have been built... – Like inventing a phonograph, and telling people how to make records that will play on it. • Good technique for providing reusable classes in a rich domain with many developers. • Existing, incompatible classes can often be retrofitted through subclasses that obey the needed interface. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-50
  • 51. Abstract interfaces Abstract interfaces in practice • Some OO languages (Java) let you formally define an interface: it's simply a set of method declarations. • Some OO languages with run-time binding (Perl5) are informal: interface is just specified by documentation; up to class user to send in an appropriate object. • Abstract interfaces form the basis of tying in Perl... objects with the right methods can become the quot;back endquot; of built-in data types like arrays and hashes! Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-51
  • 52. WHEN WORLDS COLLIDE: OO IN NON-OO DOMAINS • Pseudoclasses • Wrapper classes Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-52
  • 53. Pseudoclasses Using OOD in non-OO domains • Sometimes we don't have an OO programming language at our disposal, yet we recognize the strengths or relevance of an OO approach for a task. • Remember some of the principle goals of OO languages: – Modifiability, for code designers. – Understandability, for code users. – Reusability, for code designers and users. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-53
  • 54. Pseudoclasses What are Pseudoclasses? • Developed as a coding strategy for the C programming language, which has no classes, encapsulation, etc. Inspired by C++. • Principle can be used in nearly any non-OO language. • quot;Classesquot; are ordinary typedef'd structs. • quot;Methodsquot; are functions tied to a pseudoclass by consistent use of a conventions for: – Function naming. – Argument ordering. – Return value type and interpretation. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-54
  • 55. Pseudoclasses Pseudoclass coding standard Classnames begin with capital letter... Stack Method names have class signature as StackPush() prefix... StackPop() Symbolic constants defined for return StackOK values, with class signature as prefix... StackOVERFLOW StackEMPTY First argument of method is always StackPush(Stack *this, pointer to object in question, and Elem elem); parameter is always named quot;thisquot;... StackPop(Stack *this); Always a set of constructor functions Stack *StackNew(); for initiallizing a new object, and a StackFree(Stack *this); destructor for destroying any object... Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-55
  • 56. Pseudoclasses A sample Pseudoclass header #define StackOK 0 #define StackEMPTY -1 Return values #define StackOVERFLOW -2 typedef struct Stack { int numelems; Pointer elems[MAXELEMS]; Class definition } Stack; Stack *StackNew (); void StackFree (Stack *this); Constructors and destructors int StackPush (Stack *this, Elem elem); Elem StackPop (Stack *this); int StackSize (); Principle methods int StackDo (Stack *this, Func (*f)(Elem elem)); Iterator Stack.h Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-56
  • 57. Wrapper classes The transition to OO • Problem: although you may have acquired an OO programming environment… – We don't want to throw away or rewrite mountains of existing, tested code in Fortran, C, assembly, etc. – We may still need external non-OO libraries for which source code is complex or unavailable (e.g., X Widgets). – Some non-OO code may run much faster than code in our OO environment (e.g., C vs. Smalltalk). Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-57
  • 58. Wrapper classes What are wrapper classes? • Solution: Use wrapper classes. A wrapper class is a class where... – The instance variables hold an externally defined data structure. – The methods are quot;prettyquot; front-ends to that data structure's supporting functions. • The idea is that we provide developers with what looks like an object, but which in fact is just a thin front end onto non-OO routines. • A wrapper class is a special kind interface class... providing an encapsulated interface to foreign code! Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-58
  • 59. Wrapper classes A C++ wrapper class #include quot;Int_Stack.hquot; class IntegerStack { Int_Stack S; Instance variable is the “wrapped” int size() { data structure return s_numelems(&S); } void push(int elem) { istack_push(elem, &S); Methods are } interfaces to functions operating on the int pop() { data structure return pop_int_stack(&S); } } Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-59
  • 60. Wrapper classes Wrapping foreign code void email_file(char *eaddress, An external C routine which char *sender, has been compiled and linked char *filename); with a Smalltalk-like OOPL. method: Person A method, defined for class email: filename from: sender Person in the OOPL. Takes a file and another Person (the System sender), and emails the file. callFunc: quot;email_filequot; Real work done by sending a withArgs: [ message to the System object, (self getEmailAddress) telling it to call the installed (sender getName) function. filename ]. Typically, only simple args % (ints, floats, strings) can be passed. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-60
  • 61. Wrapper classes Wrapping and tying in Perl use GDBM_File; Here is code using the standard Perl5 wrapper class # Open database (tie to object): for accessing the GDBM tie %DB, 'GDBM_File', libraries. And it allows you to quot;mydatafile.gdbquot;, 1; use Perl's normal hash syntax! In the Perl5 world, built-in # Read and write: datatypes (like hashtables) may print quot;Id = quot;, $DB{'Id'}, quot;nquot;; be quot;tiedquot; to your own custom $DB{'Name'} = 'Janeway'; classes, as long as your classes $DB{'Rank'} = 'Captain'; provide the needed interface methods. # Close database: untie %DB; In reality, each GDBM_File object contains a number that is really a struct pointer... this number is passed in opaquely to the libgdbm.a functions. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-61
  • 62. Wrapper classes Wrapping and tying in Perl package GDBM_File; The trick was that the GDBM_File class provided all sub new { ... } the special interface methods sub DESTROY { ... } that tie() demands for tying objects to hashes... FETCH, sub FETCH { ... } # key STORE, etc. sub STORE { ... } # key, val That allowed tie() to make an sub FIRSTKEY { ... } ordinary hash variable, %DB, sub NEXTKEY { ... } into an interface to a GDBM sub DELETE { ... } # key file... without requiring the sub EXISTS { ... } # key user to learn new access methods! This is a wonderful example of # Really $x->STORE('Name', 'Kirk'): the power of encapsulation, $DB{'Name'} = 'Kirk'; polymorphism, and wrapping! Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-62
  • 63. PROJECT: MIME The story you are about to read is true. The assignment is do-able... in fact, your instructor has done it. :-) Your customer needs you to develop an email-handling system (a program that reads incoming mail, processes it, and maybe even replies to it). This is complicated by the fact that nowadays, people can send MIME mail with attachments, and any attachment can be in 1 of 5 different encodings. So you need to be able to parse multipart MIME messages... and maybe even generate them. Assume there is no software out there to do this in the language you're using. Now, design it. Copyright © 1996, 2000 Zeegee Software Inc. 09/22/06 Object-Oriented Programming 2-63