Docstoc

Implementation

Document Sample
Implementation Powered By Docstoc
					Implementation
[A&N 23 + supplement]
Converting UML classes to Java
   Item                                          price
                                    has                 Price
   -name : String
   + getPrice() : int                              0..1 + getPrice () : int

   class Item {                 Item(n,p) {              class Price {
      private name : String        name = n                 public getPrice () …
      private price : Price        price = p             }
      public getPrice () …      }
   }
                                               p = new Price()
• Map association to attribute                 a = new Item(“Ale”,p)          p : Price
• Issues, how to map:
    –   association name                        a : Item
    –   multiplicity                            name = “Ale”
    –   navigation direction                    price =
    –   aggregation & composition
    –   inheritance
                                                                                          2
Converting UML classes to Java
  Item                                                                    Discount
                                                            discounts
  -name : String                                 has                      - val: int
  + getPrice() : int          [0..1]                                *     + getValue() : int
                                                              ordered,
  + add(d : Discount)                                        nonunique    + attach(x : Item)




 class Item {                                          a = new Item(“Ale”)
    private name : String                              a.add(D)
    private discounts : List<Discount>                 a.add(D)
    public Item(…) …
    public getPrice () …                               a : Item
    public add(d:Discount) …                                                         D : Discount
                                                       name = “Ale”
 }                                                     discounts =

                                                                 : List

 Q: how do you map e.g. [0..10] multiplicity ?                                                  3
   Converting UML classes to Java
          Item                                                                                     Discount
                                           item                                      discounts
          -name : String                                          has                              - val: int
          + getPrice() : int               [0..1]                                              *   + getValue() : int
                                                                                       ordered,
          + add(d : Discount)                                                         nonunique    + attach(x : Item)

                                        Java has no direct support for bidirectional navigation.



       class Item {                                                                  class Discount {
          private name : String                                                         private val : int
          private discounts : List<Discount>                                            private item : Item
          public Item(…) …                                                              public Discount(…) …
          public getPrice () …                                                          public getValue() { return val }
          public add(d:Discount) …                                                      public attach(x:Item) …
       }                                                                             }

                                                                                 attach(x) { item = x ; x.add(this) ; }

Q: so, how to implement if we change the multiplicity of “item” from *0..1+ to 1 ?
                                                                                                                           4
Mapping aggregation & composition

        A              B      A

        A               B

• Make sure you maintain asymmetry
• For composition, make sure you don’t leak containment

                                  a2 : A
                  a1 : A
                            X
                  b:B



                                                          5
Mapping inheritance

              Parent         Coordinator
              name           reportMiss()
              addChild(c)



• Java has single inheritance
• Multiple inh.  has been discussed
• But inheritance is “static” in Java (if you make a
  parent, you can’t turn it to a coordinator at the run
  time, vice versa)
   will be discussed more in Design Pattern

                                                          6
Converting use-case / sequence diagram

•   Mapping use case  mapping seq. diagram
•   How to map interactions sequence
•   “Interaction”  a send a message m to b
•   Synchronous : sender waits for the receiver’s answer.
                charge(p)
                   ok
                               return arrow can also be implicit



• Else asynchronous
               charge(p)

• Synchronous send  method call
• Async  more complicated
                                                                   7
         Mapping “sequencing” (of interactions)


                   : System         b : Basket     c : Customer   class System {
: User                                                              buy() {
  opt      [ b.items  notEmpty() ]                                    basket = …
                          getTotalPrice()                              customer = …
         buy()                                                         if (basket.items.isEmpty()) throw …
                               totprice                                totprice = basket.getTotalPrice()
                 { totprice > 0 }                                      assert totprice > 0
                                   charge(totprice)                    customer.charge(totprice)
                                                                       basket.reset()
                                  reset()                              assert basket.items.isEmpty()
                                                                    }
                              { b.items  isEmpty() }             }

                         Notice the sync. sends.



                                                                                                     8
 It is “design” … expect to fill details.

: System          b : Basket      i : Item
                                             class Basket {
                                                items : List<Item>
      getTotalPrice()     getPrice()            …
                                                getTotalPrice() {
           totprice
                                                    int s = 0
                                                    for (Item i : items) s += i.getPrice()
                                                    return s
                                                }
                                             }




                                                                                             9
                                                                • use unique nr. to identify matching
                                                                reply/send.
   Asynchronous send                                            • you need to implement a matching
                                                                mechanism
                                                                class Customer {
                                                                   String email
  : User
                            : System                               boolean registered

       register(email)             <<create>>                     Customer(email) {
                                   Cust(email)
                                                 c : Customer        this.email = email ; …
              mail(email)                                            unique = ….
                                                                      mail(email, unique)
                                                                  }
                                              { registered }
                                                                   static mailReply(unique) {
                                      add(c)
                                                                         c = … find matching cust.
                                                                         c.activate()
Sometimes, it is not realistic to impose on synchronous
msg exchanges; e.g. the response time is long, e.g. via
                                                                    }
email. Then you will have to implement differently...

                                                                  activate() {
                                                                     registered = true ; sys.add(this)
                                                                                                  10
                                                                  }
Persistence

• Your business data is very important.
• Persistence  saving your business data
   – because your system can crash
   – because the data is too big to fit in memory
• You want to rely on dedicated persistence technology
   database
   – reliable
   – performance
   – support for query, rollback, concurrency


                                                     11
Typical architecture

      Presentation
     (User Interface)

                                                                    buys
      Business logic                          Customer                             Item
                                                                             *
                            save, load, query
   persistence layer /      Persistence layer provides an abstract interface to save, load, and query objects
                            to/from the database, that is independent from the specific database
   data access management
                            technology being used.



         database                                 Name          SureName           Age
                                                   Bob            Sponge             4
                                                 Patrick            Star             4
        Persistence
                                                   Bob              Star            40

                                                                                                      12
Relational db

• Most popular, well proven technology
• In mathematics, a relation R : A×B×C is a set of
  “tuples” from A,B,C, e.g. :

       { (a1,b1,c1), (a2,b2,c2) }

• A “table” is a relation:          A     B      C
                                    a1    b1    c1
                                    a2    b2    c2



                                                     13
Some db terms                           Product
                                         Prod      ProdName              Price
    Customer
                                           1          Mac                1000
     Name      SureName   Age              2        Toshiba              800
     Bob        Sponge     4               3              HP             1000
    Patrick      Star      4
                                        Transaction
     Bob         Star     40
                                          Name     SureName             TrNr      Prod
                                          Bob       Sponge               0           1
•   attribute
                                         Patrick          Star           1           1
•   row, column
                                          Bob       Sponge               2           2
•   key, primary key
•   foreign key
•   query                       Name   SureName    TrNr          Prod    ProdName        Price

•   joint                       Bob     Sponge        0           1            Mac       1000
                                Bob     Sponge        2           2          Toshiba     800



                                                                                                 14
Mapping class to table

  Customer             Customer
  Name                 OID   Name          Email        creationTime   UpdateCtr
  Email                10    Bob       bob@bikini.com       …             …
  OID
                       11    Patrick   pat@bikini.com       …             …
  creationTime
  UpdateCtr



• You may need to add “shadow” attributes to support
  persistence
   – Object ID
   – Creation time
   – Update counter


                                                                              15
Mapping 1-to-many association

 Customer        *   lives in      1 City
 Name                                Code
 Email                               Name

 Customer                                     City
 OID   Name           Email           City     OID   Code     Name
 10    Bob       bob@bikini.com      AMS       0     AMS    Amsterdam
 11    Patrick    pat@bikini.com      UTR      1     UTR     Utrecht




                 Via a foreign key on the “many”-side




                                                                        16
Mapping many-to-many association

 Customer        *                      buys                           * Item
 Name                                                                     Name
 Email                                                                    Price
                                 Transaction
                                 Date

 Customer                                                          Item
 OID   Name              Email                                     OID    Name      Price
 10    Bob           bob@bikini.com                                0      Mac       1000
 11    Patrick       pat@bikini.com                                1      Toshiba   800


                                 Transaction
                                 Date      Customer        Item
                                 …             10              0
                                 …             10              1
                                 With an association table..
                                                                                            17
Mapping inheritance

Item                        • map the entire inheritance hierarchy to
                   PC
Name                        a single table, or :
                   OpSys
Price
                            • map each class to its own table

  Item                      PC
   OID   Name       Price   OID   OpSys
   1     USB 10      10     10    MacOS
   10    iMac       1000    11    Vista
   11    Toshiba    800
                            12    Vista
   12    HP         800




                                                                        18
Saving and loading objects

• When you “load” a customer x, do you also expect that all
  objects navigable from x to be loaded as well?
• Similarly, when you save x, do you need to also save all
  objects navigable from x?

   “Bob”          “Patrick”       ID   Name        Email        ID1   ID2
bob@bikini.com   pat@bikini.com
                                  10 Bob       bob@bikini.com   10    11
                                  11 Patrick   pat@bikini.com   5     10
                   “Octo”
                 boss@octo.net    5    Octo    boss@octo.net    5     11
                                                                11    5

• From OO perspective: yes.
• Additional implementation work 
                                                                           19
Impedance mismatch

• Between your OO application and its relational db
  back-end.
• Objects’ “graph” structure do not map directly to
  tables.
• Issues:
   – how to save/load/query such a structure to/from tables?
   – what to do with concurrent access ? (you can potentially
     pull a large graph of objects)
• Available solutions:
   – Semi-automating it with a mapping framework
   – Use an object-relational DB instead
   – Use an OO DB
                                                                20
Not used, future backup




                          21
Some guide lines..

• Maintenance can be quite expensive! Important contributing
  aspects:
   – Complexity  hard to understand, buggy, cost to fix bugs, testing cost
   – Flexibility  if bad, then changing or adding features can be a real
     pain
• Strategically towards those, important “variables” to balance:
       •   Encapsulation
       •   Coupling
       •   Cohesiveness
       •   Inheritance

• Tactically: design patterns, refactoring, coding style,…
                                                                          22
“Encapsulation”

• Meaning ….
  – Hiding some part of your data/functionalities
  – packing related functionalities into one unit, and exposing
    only the needed one for public use.
• Software built from encapsulated units is less
  complex.
• OO gives you powerful mechanism for encapsulation




                                                              23
Balancing…

• A cohesive class is easier to understand
• Low coupling between classes contribute to less overall
  complexity
• But often you have to balance them…
                                                 delegation…
    Product
    - name : String                            1 Currency
                                                  - code : String
    - price : int // e.g. in euro
                                                  + covert(c : Currency)
    + getPrice(c : Currency) : Int
    will have to do the currency conversion
    himself, which is not really a job for a
    Product.




                                                                           24
Balancing…

• Inheritance let you reuse code (less maintenance), but you get
  implicit coupling with superclasses.

• Beware of deep inheritance trees

   Programmer may overlook influence of a superclass that is far
   up in the tree.


 Duration
                 Discount                         Registered
 - start                         MemberDiscount
                 - val                            Customer
 - end
                 + getValue ()
 + isValid()



                                                               25
Balancing…
• When coding it is convenient to be able to access an object’s
  operations at will, but this introduces coupling.
• Demeter “Law” (Holland 87): an object should only talk with
  its neighbors.
           Customer                                         * Item
                                 Basket
           getPrice()                                         getPrice()



           Customer            Basket                      * Item
           getPrice()          getPrice()                    getPrice()

                           Meet Demeter, but in a way we trade
                           off with Basket’s cohesiveness

• More structural: you open up many attributes/operations as package-
  private. But then all classes in the package are coupled together! You may
  pay the price when you want to modify some of them.
                                                                           26
Software metric

• Quantitative indicator of a certain aspect of
  your program, e.g. its complexity.
  – Can be calculated with a tool
  – Help you to decide whether or not to refactor
  – Useful as a strategic instrument
• Examples:
  – Line numbers
  – Counting coupling, inheritance depth etc
  – Halstead
  – Mc Cabe
                                                    27
                                                                Just for info



Halstead

Halstead approximates complexity in terms of effort to
“read” the program:

      x = x + x ; x++            x = x + y ; z++




                                                         (alleen ter info)




                                                                 28
                                                              Just for info



Mc Cabe
Mc Cabe approximates complexity in the numbers of “linearly
independent” execution paths through the program.

int P() {
  if (...) return 100                        0
  else return 0
}
                                                      4
                                      1
                                                 3
               0

                                  2
       1
                         2                       5

     Control Flow Graph (CFG)

                                                               29
                                                                     Just for info



Metric for encapsulation etc for OO

• Chen & Lu, 1993; simple, to “count”:
   –   Encapsulation
   –   Coupling
   –   Cohesiveness
   –   Inheritance
• CL approximate encapsulation”of a class C by the sum of
  signature complexity of its public method.
   – more parameters  more complex
   – complex typed parameter                Type        complexity
       increases complexity                              value
                                         boolean, int       0
                                           double           2
                                           object          6-9

                                                                      30
Inheritance and cohesion

• CL approximate complexity due inheritance on a
  class C by the sum of:
   –    # C’s methods (own + inh)
   –    C’s inheritance distance
   –    # C’s direct superclasses
   –    # C’s subclasses

• CL approx. cohesion by counting the number of groups of
  “related” methods in C.
   – Put method with “similar” param-types in the same group:

       add(discount), setName(name), remove(discount)
                                                                31
     Tool support




32
                    32
Issues (in persistence)

• Mapping: how to map your objects to the back-end
  DB
• When you anticipate multiple users:
   – Performance
      • Optimizing your logical & physical data model
   – Concurrency
   – Security
• We’ll discuss some of these
• Related courses: db, distributed programming,
  cryptography
                                                        33
Some db terms                              Product
                                            Prod      ProdName              Price
    Customer
                                              1          Mac                1000
     Name      SureName   Age                 2        Toshiba              800
     Bob        Sponge     4                  3              HP             1000
    Patrick      Star      4
                                           Transaction
     Bob         Star     40
                                             Name     SureName             TrNr        Prod
                                             Bob       Sponge               0           1
•   attribute
                                            Patrick          Star           1           1
•   row, column
                                             Bob       Sponge               2           2
•   key, primary key
•   foreign key
•   query                       Name      SureName    TrNr          Prod    ProdName          Price

•   joint                        Bob       Sponge        0           1            Mac         1000
                                Patrick     Star         1           1            Mac         1000
                                 Bob       Sponge        2           2          Toshiba       800
                                                                     3            HP          1000    34
Map to normalized tables…
• What if we store our data like this?

   ID         Name      Email               TrNr   Prod    ProdName    Price
   1035       Bob       bob@bikini.com        1    1       Mac         1000
   1123       Patrick   pat@bikini.com        2    2       Toshiba     800
   1123       Patrick   pat@bikini.com        3    1       Mac         1000
                                                   3       HP          1000

     we only need 1x table
     data redundancy  wasting space + consistency problem
     have to deal with “anomalies”, e.g. what to do if we want to delete Patrick ?
     certain queries may be faster

• Several “normal forms” to eliminate data redundancy
• sometimes “de-normalize” to make certain queries faster
                                                                                  35
  Look at attributes dependencies

  • Let A,B,C be attributes in a table T
  • A,B  C = C “depends on” A,B = if the values of AB uniquely
    determines the value of C
  • Let K = ,A,B- be a “candidate” key of T ; C partially depends K
    if it only depends on part of K  redundancy.


            ID       Name         Email         TrNr   Prod   ProdName   Price

           1035      Bob      bob@bikini.co      1      1       Mac      1000
                                  m
not 2NF
           1123     Patrick   pat@bikini.com     2      2     Toshiba    800
           1123     Patrick   pat@bikini.com     2      1       Mac      1000
             0      dummy                        0      3       HP       1000

          TrNr  Prod is a candidate key here                                    36
So-called 2nd Normal Form

• Table T is 2NF if it contains no partial dependency wrt any
  candidate key.
• Transform the previous scheme:


          ID             Name               Email          TrNr        Prod       ProdName     Price




                                                                  TrNr    Prod          Prod    ProdName    Price
    ID         Name                 Email           TrNr
                                                                   1          1          1         Mac      1000
   1035         Bob         bob@bikini.com           1
                                                                   2          2          2       Toshiba    800
   1123        Patrick          pat@bikini.com       2
                                                                   2          1          3             HP   1000
    0          dummy                                 0
                                                                   0          3


• Make sure you don’t lose information!
                                                                                                             37
3rd Normal Form
• T is 3NF if it is 2NF, and every attribute A which is not part of a
  candidate key, must depend only on a candidate key.

                   ID               Name               Email          TrNr

                   1035             Bob         bob@bikini.com          1
  not 3NF
                   1123          Patrick        pat@bikini.com          2

                   1123          Patrick        pat@bikini.com          3

                    0            dummy                                  0


                                                                 ID          TrNr
            ID            Name                 Email
                                                                 1035         1
            1035           Bob            bob@bikini.com
                                                                 1123         2
                                                                                    3NF
            1123          Patrick          pat@bikini.com
                                                                 1123         3
             0          dummy
                                                                  0           0
                                                                                          38
Denormalization
                     ID               Name               Email          TrNr

                     1035             Bob         bob@bikini.com          1
    not 3NF
                     1123          Patrick        pat@bikini.com          2

                     1123          Patrick        pat@bikini.com          3

                      0            dummy                                  0


                                                                   ID          TrNr
              ID            Name                 Email
                                                                   1035         1
              1035           Bob            bob@bikini.com
                                                                   1123         2
                                                                                      3NF
              1123          Patrick          pat@bikini.com
                                                                   1123         3
               0          dummy
                                                                    0           0


• But what if you frequently query the customers names and emails
  of given transactions?  you will need to join often
• To favor query speed : denormalize.
                                                                                            39
You may have seen this: entity Relationship
(ER) model …
Customer                                                                Product
                                purchase
ID {PK}            *                                 *                  ID {PK}
                                  date
Name                                                                    Name
                                   nr
Email                                                                   Price



Customer                                             Product
ID     Name            Email                         ID       Name           Price
10     Bob       bob@bikini.com                      1        Mac            1000
11     Patrick   pat@bikini.com                      2        Toshiba         800


                               Purchase
                                nr   date   CustID        ItemID
                                1    ...    10            1
                                2    ...    11            1
                                2    ...    11            2
                                                                                     40
Typical architecture

      Presentation
     (User Interface)

                                                                    buys
      Business logic                          Customer                             Item
                                                                             *
                            save, load, query
   persistence layer /      Persistence layer provides an abstract interface to save, load, and query objects
                            to/from the database, that is independent from the specific database
   data access management
                            technology being used.

                            ID      Name       Email                TrNr    Prod    ProdName       Price

         database           1035    Bob        bob@bikini.com         1     1       Mac            1000

                            1123    Patrick    pat@bikini.com         2     2       Toshiba        800

        Persistence         1123    Patrick    pat@bikini.com         3     1       Mac            1000

                                                                            3       HP             1000

                                                                                                      41
Concurrency                    clients
                                 A
                                 B
        db      App
                                  C




• Each functionality invoked by a client may require data
  from certain tables, and update to some rows.
• Danger: collision.  you need to lock your data!
• Pessimistic locking  safe, but does not perform
• Optimistic locking
   – Blow up the complexity of your persistence layer
   – Error prone

                                                        42

				
DOCUMENT INFO