42
Implementation [A&N 23 + supplement]

Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

  • View
    215

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

Implementation[A&N 23 + supplement]

Page 2: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

2

Converting UML classes to Java

• Map association to attribute• Issues, how to map:

– association name– multiplicity– navigation direction– aggregation & composition– inheritance

Item-name : String+ getPrice() : int

Price+ getPrice () : int

has price

class Item { private name : String private price : Price public getPrice () …}

class Price { public getPrice () …}

0..1

p = new Price() a = new Item(“Ale”,p) p : Price

a : Itemname = “Ale”price =

Item(n,p) { name = n price = p}

Page 3: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

3

Converting UML classes to Java

Item-name : String+ getPrice() : int+ add(d : Discount)

Discount- val: int+ getValue() : int+ attach(x : Item)

has*

ordered, nonunique

[0..1]

discounts

class Item { private name : String private discounts : List<Discount> public Item(…) … public getPrice () … public add(d:Discount) …}

a = new Item(“Ale”) a.add(D) a.add(D)

a : Itemname = “Ale”discounts =

D : Discount

Q: how do you map e.g. [0..10] multiplicity ?

: List

Page 4: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

4

Converting UML classes to Java

Item-name : String+ getPrice() : int+ add(d : Discount)

Discount- val: int+ getValue() : int+ attach(x : Item)

has*

ordered, nonunique

[0..1]

discountsitem

Java has no direct support for bidirectional navigation.

class Discount { private val : int private item : Item public Discount(…) … public getValue() { return val } public attach(x:Item) …}

class Item { private name : String private discounts : List<Discount> public Item(…) … public getPrice () … public add(d:Discount) …}

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

Q: so, how to implement if we change the multiplicity of “item” from [0..1] to 1 ?

Page 5: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

5

Mapping aggregation & composition

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

A B

A B

A

a1 : A

b : B

a2 : A

X

Page 6: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

6

Mapping inheritance

• 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

ParentnameaddChild(c)

CoordinatorreportMiss()

Page 7: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

7

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.

• Else asynchronous

• Synchronous send method call• Async more complicated

charge(p)

return arrow can also be implicit

charge(p)

ok

Page 8: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

8

Mapping “sequencing” (of interactions)

: System b : Basket

getTotalPrice()

c : Customer

totprice

charge(totprice)

reset()

{ totprice > 0 }

{ b.items isEmpty() }

opt [ b.items notEmpty() ]

class System { buy() { basket = … customer = … if (basket.items.isEmpty()) throw … totprice = basket.getTotalPrice() assert totprice > 0 customer.charge(totprice) basket.reset() assert basket.items.isEmpty() }}

buy()

Notice the sync. sends.

: User

Page 9: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

9

It is “design” … expect to fill details.

: System b : Basket

getTotalPrice()

i : Item

getPrice()

totprice

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

Page 10: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

10

Asynchronous send

: System

register(email)

• use unique nr. to identify matching reply/send.• you need to implement a matching mechanism

mail(email)

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...

: User

c : Customer<<create>>Cust(email)

{ registered }

class Customer { String email boolean registered

Customer(email) { this.email = email ; … unique = …. mail(email, unique) }

static mailReply(unique) { c = … find matching cust. c.activate() }

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

add(c)

Page 11: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

11

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

Page 12: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

12

Typical architecture

Presentation(User Interface)

Business logic

database

persistence layer /data access management

Persistence

Customer Item*

buys

save, load, queryPersistence layer provides an abstract interface to save, load, and query objects to/from the database, that is independent from the specific database technology being used.

Name SureName Age

Bob Sponge 4

Patrick Star 4

Bob Star 40

Page 13: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

13

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

Page 14: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

14

Some db terms

• attribute• row, column• key, primary key• foreign key• query• joint

Prod ProdName Price

1 Mac 1000

2 Toshiba 800

3 HP 1000

Name SureName Age

Bob Sponge 4

Patrick Star 4

Bob Star 40

Customer

Product

TransactionName SureName TrNr Prod

Bob Sponge 0 1

Patrick Star 1 1

Bob Sponge 2 2

Name SureName TrNr Prod ProdName Price

Bob Sponge 0 1 Mac 1000

Bob Sponge 2 2 Toshiba 800

Page 15: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

15

Mapping class to table

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

CustomerNameEmail

OID Name Email creationTime UpdateCtr

10 Bob [email protected] … …

11 Patrick [email protected] … …

Customer

OIDcreationTimeUpdateCtr

Page 16: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

16

Mapping 1-to-many association

CustomerNameEmail

CityCodeName

* 1lives in

OID Name Email City

10 Bob [email protected] AMS

11 Patrick [email protected] UTR

OID Code Name

0 AMS Amsterdam

1 UTR Utrecht

Customer City

Via a foreign key on the “many”-side

Page 17: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

17

Mapping many-to-many association

CustomerNameEmail

ItemNamePrice

* *buys

OID Name Email

10 Bob [email protected]

11 Patrick [email protected]

OID Name Price

0 Mac 1000

1 Toshiba 800

Customer Item

TransactionDate

Date Customer Item

… 10 0

… 10 1

Transaction

With an association table..

Page 18: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

18

Mapping inheritance

ItemNamePrice

PCOpSys

OID OpSys

10 MacOS

11 Vista

12 Vista

OID Name Price

1 USB 10 10

10 iMac 1000

11 Toshiba 800

12 HP 800

• map the entire inheritance hierarchy to a single table, or :• map each class to its own table

Item PC

Page 19: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

19

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?

• From OO perspective: yes.• Additional implementation work

“Bob”[email protected]

“Patrick”[email protected]

“Octo”[email protected]

ID Name Email

10 Bob [email protected]

11 Patrick [email protected]

5 Octo [email protected]

ID1 ID2

10 11

5 10

5 11

11 5

Page 20: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

20

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

Page 21: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

21

Not used, future backup

Page 22: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

22

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:

• Tactically: design patterns, refactoring, coding style,…

• Encapsulation• Coupling• Cohesiveness• Inheritance

Page 23: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

23

“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

Page 24: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

24

Balancing…

• A cohesive class is easier to understand• Low coupling between classes contribute to less overall

complexity• But often you have to balance them…

Product - name : String - price : int // e.g. in euro+ getPrice(c : Currency) : Int

Currency- code : String+ covert(c : Currency)

1

will have to do the currency conversion himself, which is not really a job for a Product.

delegation…

Page 25: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

25

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- start- end+ isValid()

MemberDiscount RegisteredCustomer

Discount- val+ getValue ()

Page 26: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

26

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.

• 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.

BasketItemgetPrice()

CustomergetPrice()

BasketgetPrice()

ItemgetPrice()

CustomergetPrice()

*

*

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

Page 27: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

27

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

Page 28: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

28

Halstead

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

(alleen ter info)

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

Just for info

Page 29: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

29

Mc Cabe

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

0

12

Control Flow Graph (CFG)

0

13

2

4

5

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

Just for info

Page 30: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

30

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

increases complexity

Just for info

Type complexityvalue

boolean, int 0

double 2

object 6-9

Page 31: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

31

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)

Page 32: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

32

Tool support

32

Page 33: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

33

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

Page 34: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

34

Some db terms

• attribute• row, column• key, primary key• foreign key• query• joint

Prod ProdName Price

1 Mac 1000

2 Toshiba 800

3 HP 1000

Name SureName Age

Bob Sponge 4

Patrick Star 4

Bob Star 40

Customer

Product

TransactionName SureName TrNr Prod

Bob Sponge 0 1

Patrick Star 1 1

Bob Sponge 2 2

Name SureName TrNr Prod ProdName Price

Bob Sponge 0 1 Mac 1000

Patrick Star 1 1 Mac 1000

Bob Sponge 2 2 Toshiba 800

3 HP 1000

Page 35: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

35

Map to normalized tables…

• What if we store our data like this?

• Several “normal forms” to eliminate data redundancy• sometimes “de-normalize” to make certain queries faster

ID Name Email TrNr Prod ProdName Price

1035 Bob [email protected] 1 1 Mac 1000

1123 Patrick [email protected] 2 2 Toshiba 800

1123 Patrick [email protected] 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

Page 36: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

36

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 AB 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 [email protected]

1 1 Mac 1000

1123 Patrick [email protected] 2 2 Toshiba 800

1123 Patrick [email protected] 2 1 Mac 1000

0 dummy 0 3 HP 1000

TrNr Prod is a candidate key here

not 2NF

Page 37: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

37

So-called 2nd Normal Form

• Table T is 2NF if it contains no partial dependency wrt any candidate key.

• Transform the previous scheme:

• Make sure you don’t lose information!

TrNr Prod

1 1

2 2

2 1

0 3

Prod ProdName Price

1 Mac 1000

2 Toshiba 800

3 HP 1000

ID Name Email TrNr Prod ProdName Price

ID Name Email TrNr

1035 Bob [email protected] 1

1123 Patrick [email protected] 2

0 dummy 0

Page 38: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

38

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 [email protected] 1

1123 Patrick [email protected] 2

1123 Patrick [email protected] 3

0 dummy 0

not 3NF

ID TrNr

1035 1

1123 2

1123 3

0 0

ID Name Email

1035 Bob [email protected]

1123 Patrick [email protected]

0 dummy

3NF

Page 39: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

39

Denormalization

• 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.

ID Name Email TrNr

1035 Bob [email protected] 1

1123 Patrick [email protected] 2

1123 Patrick [email protected] 3

0 dummy 0

not 3NF

ID TrNr

1035 1

1123 2

1123 3

0 0

ID Name Email

1035 Bob [email protected]

1123 Patrick [email protected]

0 dummy

3NF

Page 40: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

40

You may have seen this: entity Relationship (ER) model …

CustomerID {PK}NameEmail

ProductID {PK}NamePrice

*

ID Name Email

10 Bob [email protected]

11 Patrick [email protected]

CustomerID Name Price

1 Mac 1000

2 Toshiba 800

Product

nr date CustID ItemID

1 ... 10 1

2 ... 11 1

2 ... 11 2

Purchase

purchasedate

nr

*

Page 41: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

41

Typical architecture

Presentation(User Interface)

Business logic

database

persistence layer /data access management

Persistence

Customer Item*

buys

save, load, query

ID Name Email TrNr Prod ProdName Price

1035 Bob [email protected] 1 1 Mac 1000

1123 Patrick [email protected] 2 2 Toshiba 800

1123 Patrick [email protected] 3 1 Mac 1000

3 HP 1000

Persistence layer provides an abstract interface to save, load, and query objects to/from the database, that is independent from the specific database technology being used.

Page 42: Implementation [A&N 23 + supplement]. Converting UML classes to Java Map association to attribute Issues, how to map: – association name – multiplicity

42

Concurrency

• 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

Appdb

A

clients

B

C