Implement Ac I On

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

Taller Paw Implementacin de Diseno a Codigo

18/06/12

PAW de Diseo a Implementacin

Review of Last Lecture


n

Design Patterns:
q q q q q q q q

Abstraction-Occurrence General-Hierarchy Composite Faade Player-Role State Singleton Observer

18/06/12

PAW de Diseo a Implementacin

Overview of This Lecture


n n

Basic Implementation Steps. Implementing Classes:


q

Class Association:
n n n n

Navigation direction; Multiplicity constraint; Qualified associations; Association classes.

18/06/12

PAW de Diseo a Implementacin

Basic Steps in Implementation


n

Define method interface:


q

Give a formal/informal description of the functionality of an operation. Useful in reducing misunderstanding and allows splitting the workload. Which class/subsystem to start.

Decide the order of implementation:


q

Implement the design using a suitable programming language.


PAW de Diseo a Implementacin 4

18/06/12

Defining Method Interface


n

During design:
q

Detailed information about the method header are defined: n Returned Type, Parameter Type; n Accessibility. What should the method do? What are acceptable values for the parameter? Etc

However, the functionality is not formally defined:


q q q

Even more important for complicated operations.

18/06/12

PAW de Diseo a Implementacin

Operation Contract
n n

Writing the operation contract is one possible way to define the functionality. Define the precondition:
q

Express the constraint regarding the attributes of the class and the actual parameter. Express the effect of an operation:
n n n

Define the postcondition:


q

Instance Creation/Deletion; Attribute Modification; Association Formed/Broken.

Description can scale in formality.


PAW de Diseo a Implementacin 6

18/06/12

Operation withdraw()Contract: Example


BankAccount -balance +deposit( amt : float ) +withdraw( amt: float )

Precondition: - amt > 0 - amt <= balance Postcondition: - New balance = Old balance - amt

18/06/12

PAW de Diseo a Implementacin

Order of Implementation
n

Many classes with dependencies in the design:


q

Need an order of implementation. Top-Down:


n n

Two basic strategies:


q

Starts with high-level components. Then continue to implement the dependent components. Starts with the lower level classes, i.e., classes with least dependency. Then proceed to code classes that make use of the implemented classes.

Bottom-Up:
n

18/06/12

PAW de Diseo a Implementacin

Example
A
methodA() myB

B
methodB()

{ myB.methodB(); }

A depends on B, i.e., A make use of B


n

may be an attribute in class A of class B; The navigability is one possible indicator of the dependency.
myB
PAW de Diseo a Implementacin 9

18/06/12

Top Down Implementation


n n

Starts with Class A, then Class B. Advantages:


q

Class A represents a higher level component as it makes use of other classes. Starting with high level components enables early validation of the overall system. Need temporary implementation (known as stub) for lower classes. Example: n A temporary implementation of methodB() is needed for the implementation of methodA().
PAW de Diseo a Implementacin 10

Disadvantages:
q

18/06/12

Bottom Up Implementation
n n

Starts with Class B, then Class A. Advantages:


q q

Low level classes can usually stand alone. No need for stub. Have to postpone the generation of a complete executable program.

Disadvantages:
q

18/06/12

PAW de Diseo a Implementacin

11

Class Diagram Implementation

18/06/12

PAW de Diseo a Implementacin

12

Implementing Classes
n

Basic mapping:
q

q q

A UML Class is implemented by a class in Java, C+ +, etc; Attributes are implemented by fields; Operations are implemented by methods. E.g., the implementation of abstract classes, interfaces, and generalization.

There may be some language specific issues:


q

18/06/12

PAW de Diseo a Implementacin

13

Example: The Booking Class


# # + + + public abstract class Booking { protected int covers; protected Date date; protected Booking(int c, Date d) { covers = c; date = d; } public void setCovers(int c) { covers = c; } public Date getDate() { return date; } public void setArrivalTime(Time t) { } }

The getCovers(c:Integer) operation should be setCovers(c:Integer).


18/06/12 PAW de Diseo a Implementacin 14

Example: Generalization
public class WalkIn extends Booking { public WalkIn(...) { ... } } public class Reservation extends Booking { Time arrivalTime ; public Reservation(...) { ... } public void setArrivalTime(Time t) { arrivalTime = t ; } }

18/06/12

PAW de Diseo a Implementacin

15

Implementing Associations
n

Associations (Class Diagram) describe properties of links (Object Diagram).

Account :Account
n n n n

Guarantor :Guarantor

A link gives one object access to another and enables message passing. Java: References (C++: Object Pointer) share these properties, so associations can be implemented with references. References support only one direction of navigation.
q

Should restrict navigability to make implementation easier.

References should not be manipulated explicitly by other classes.


PAW de Diseo a Implementacin 16

18/06/12

Optional Unidirectional Association


n

Distinction between associations:


q q

direction; multiplicity. a reference to another object; or the null reference.

Reference variables can hold:


q q

So the default multiplicity of a reference is 0..1.

18/06/12

PAW de Diseo a Implementacin

17

Implementation
n

The association is defined by a field in the Account Java class holding a reference to an instance of the DebitCard Java class:
public class Account { private DebitCard theCard ; ... } Good match for simple object reference.

Account

0..1

DebitCard

18/06/12

PAW de Diseo a Implementacin

18

Maintaining the Association


n

As only Account is aware of this association, it should also maintain the association:
q q

Setup/Removal of the link; Appropriate methods for accessing the linked object.
public DebitCard getCard(){ return theCard; } public void setCard(DebitCard card){ theCard = card; }

e.g.

Return the linked object to outsider

Changing the linked object

18/06/12

PAW de Diseo a Implementacin

19

Mutability for Association


n

The last example assumes that the DebitCard association is mutable: q An Account object can be linked to a different DebitCard object during its lifetime. Hence, it makes sense to have the following methods for setup/removal the link:
public void setCard(DebitCard card){ theCard = card; } public void removeCard( ) { theCard = null; }

18/06/12

PAW de Diseo a Implementacin

20

Immutable Association
n n

Some associations are immutable:


q

once assigned, a link must not be altered.

The designer can state this in the class diagram:


{Immutable}

The programmer has to check the links existence explicitly:


public void setCard(DebitCard card) { if (theCard != null) { // throw ImmutableAssociationException } theCard = card ; }

Explicit Check to maintain Immutable link

18/06/12

PAW de Diseo a Implementacin

21

Compulsory Association
n n

Multiplicity with lowerbound larger than 0 is compulsory, i.e., At all times, the link(s) cannot be null . Example:

The above means An Account object must have exactly one link to a Guarantor object at all times . Programmers have to check explicitly to ensure this is true.

18/06/12

PAW de Diseo a Implementacin

22

Implementation
n

The earliest possible opportunity to setup the link is in the constructor method:
public Account(Guarantor g) { if (g == null) { // throw NullLinkError } theGuarantor = g ; }

Make sure we have a guarantor

If the association is mutable, similar checks must be performed in methods that changes the link, e.g.:
public setGuarantor(Guarantor g) { if (g == null) { // throw NullLinkError } theGuarantor = g ; }

Make sure we have a guarantor

18/06/12

PAW de Diseo a Implementacin

23

1-to-Many Unidirectional Association


n

Some associations require more than one link to be stored:

Data structures, such as arrays and vectors, can be used to store the references.
q

For a specific upper bound, e.g., 08 , specific checks must be implemented:


public class Manager { private ArrayList theAccounts ; public void addAccount(Account acc) { theAccounts.add(acc) ;
}

Stores * Accounts references.

}
18/06/12 PAW de Diseo a Implementacin 24

Bidirectional Association
n

Some associations need to be navigated in both directions:


q

because references are unidirectional, it will take two references to implement a bidirectional link; the association can be implemented by including a suitable field in each of the associated classes.
Account DebitCard
Bidirectional Association stated in Class Diagram

Account
theCard: DebitCard

theCard theAccount

DebitCard
theAccount: Account

Closest implementation of the Class Diagram in Java or C++


25

18/06/12

PAW de Diseo a Implementacin

Bidirectional Association Implementation

n n

DebitCard is optional ( 0..1 from Account). Account is compulsory ( 1 from DebitCard).

Hence, the best way to satisfy the conditions is:


q

Create the Account first, then the DebitCard:


{ Account acc1 = new Account() ; DebitCard aCard = new DebitCard(acc1) ; acc1.setCard(aCard) ; }

Question: Why is that the order of associations creation to satisfy the conditions? 18/06/12 PAW de Diseo a Implementacin 26

Referential Integrity
n

The bidirectional association is implemented as two separate references, it is important to keep them consistent.
q q

The links should be inversed one to each other. Known as referential integrity.

Example of referential integrity violation:


Account acc1 = new Account() ; Account acc2 = new Account() ; DebitCard aCard = new DebitCard(acc1); acc2.setCard(aCard) ;
theCard

acc2: Account acc1: Account

aCard: DebitCard

theAccount

The two links do not correspond to a valid bidirectional association!

18/06/12

PAW de Diseo a Implementacin

27

Maintaining Referential Integrity


n

The problem with the example code on slide 27:


q

creation and reference setup (setCard() method) are two separate operations. Responsibility of programmer to make sure the two operations are performed in a consistent fashion.
DebitCard

To minimize the human error, delegate one of the classes to maintain the referential integrity instead. Example:
public class Account { private DebitCard theCard ; public void addCard() { theCard = new DebitCard(this); } // other methods as well } Account class handles both the DebitCard creation and reference setting.

18/06/12

PAW de Diseo a Implementacin

28

Joint Creation of Objects

Suppose an association is intended to be immutable and also needs to be traversed in both directions. Constructors of both classes should take in an instance of the other to satisfy the constraint specified by the class diagram.
q q

Java and C++ do not allow simultaneous object creation. Must create one of the objects with the default constructor, i.e., to violate the constraint for a short time.
PAW de Diseo a Implementacin 29

18/06/12

Code Example
n

Attempts to satisfy the compulsory link:


Account a = new Account(g) ; Guarantor g = new Guarantor(a) ; Account a = new Account(new Guarantor(a)) ; Guarantor g = a.getGuarantor( ) ;

g is not initialized. a is not initialized. g is initialized by default constructor, no Account reference. Setup the reference after Account a is properly initialized.

Have to violate the constraint for a while:


Guarantor g = new Guarantor( ) ; Account a = new Account(g) ; g.setAccount(a) ;

18/06/12

PAW de Diseo a Implementacin

30

Implementing Bidirectional Association

Class Diagram

myG

Account
myG: Guarantor
getMyG( ): Guarantor setMyG( Guarantor )
myA

Guarantor
myA: Account
getMyA ( ): Account setMyA ( Account ) Possible Implementation

Some likely methods

18/06/12

PAW de Diseo a Implementacin

31

Maintaining Bidirectional Association


n n

Methods that change the reference should maintain referential integrity. Take setMyG() for example: q Have to set the reversed link too. q If Account has already a Guarantor:
n n

Either do not allow the link change. OR, remove the link with previous Guarantor.
oldG: Guarantor newG: Guarantor
a.SetMyG(newG)

a :Account

The Reverse link has to be removed too.

18/06/12

PAW de Diseo a Implementacin

32

Code Example
//Class Account public void setMyG(Guarantor newG) { if (newG == null) //throw NullLinkError if (myG != null && myG != newG) { //previous Guarantor exists myG.removeMyA(this); } if (myG == newG) return; myG = newG; //set the reverse link myG.setMyA(this); }

//Class Guarantor void removeMyA(Account a) { //only allows holder of //the reverse link call //this method if (a == myA) myA = null; }

18/06/12

PAW de Diseo a Implementacin

33

Code Example (Cont)


//Class Guarantor public void setMyA(Account newA) { if (newA == null) //throw NullLinkError if (myA != null && myA != newA) { //previous Guarantor exists myA.RemoveMyG(this); } if (myA == newA) return; myA = newA; //set the reverse link myA.setMyG(this); }

//Class Account void RemoveMyG(Guarantor g) { //only allows holder of //the reverse link call //this method if (g == myG) myG = null; }

18/06/12

PAW de Diseo a Implementacin

34

Observations
n

Even with the complicated code, there are still some problems:
q q

The old guarantor will be without an Account object. Mutual recursive functions:
n

setMyA calls setMyG, which calls setMyA.

Very easy to get into infinite loop.

Should avoid compulsory bidirectional association if possible. If bidirectional association must be used, immutability is recommended to curb the coding complexity.
PAW de Diseo a Implementacin 35

18/06/12

One-to-Many Association

Raise no new issues:


q q

Customer holds a collection of references. Account holds a non-null reference.

is a better choice as the maintainer for the referential integrity:


Customer
q

q
18/06/12

It provides a method like addAccount() that creates a new account and setup the reference. Similar to the addCard() method on slide 30.
PAW de Diseo a Implementacin 36

Many-to-Many Association

Previously discussed implementation techniques can be used. Recommendation:


q q

Allows only one of the classes to modify the links. E.g., It makes sense to allow only the Customer to change links to Accounts and maintain the reversed link also. Simplify the implementation as the coding logic can be considered from one direction only.

18/06/12

PAW de Diseo a Implementacin

37

Many-to-Many Association

Another implementation technique is to reify the association:

The new class (e.g., Signatory in the example above) is in a good position to maintain referential integrity.
:Account :Signatory :Customer

18/06/12

PAW de Diseo a Implementacin

38

Qualified Association

The purpose of a qualifier is often to provide efficient access to linked objects:


q

For example, to access accounts given only the account number; Also to avoid a linear search through all accounts.

18/06/12

PAW de Diseo a Implementacin

39

Implementing Qualifier
n

The run-time structure involves some kind of index to accounts:

Using accno as index.

18/06/12

PAW de Diseo a Implementacin

40

Code Example
n

Hash Table is a good choice to implement the index:

public class Bank{ private HashTable theAccounts; public void addAccount (Account a) { theAccounts.put(new Integer(a.getNumber()), a); } put (Object Key, Object Value) public void removeAccount(int number) { theAccounts.remove(new Integer(number)); } public Account lookupAccount(int number) { return (Account) theAccounts.get(new Integer(number)); } get(Object Key): Object

18/06/12

PAW de Diseo a Implementacin

41

Hash table - reminder


n

It means a data structure that associates keys with values. The primary operation it supports efficiently is a lookup: given a key (e.g., a person's name), find the corresponding value (e.g., that person's telephone number). It works by transforming the key using a hash function into a hash, a number that is used to index into an array to locate the desired location ("bucket") where the values should be.

18/06/12

PAW de Diseo a Implementacin

42

Hash table - reminder

Like arrays, hash tables provide constant-time O(1) lookup on average, regardless of the number of items in the table.
PAW de Diseo a Implementacin 43

18/06/12

Association Class

Common strategy:
q

Transform the association class into a simple class; replacing it by two associations.

18/06/12

PAW de Diseo a Implementacin

44

Implementing Association Class


Module *
Registration
Class Diagram

Student

Module *
Class Diagram

Student
1

Registration
Mark: Integer

Mark: Integer

:Module
:Registration
Mark = 76

:Student

:Module
:Registration
Mark = 76

:Student

:Student
:Registration
Object Diagram

:Student
:Registration
Object Diagram

Mark = 89

Mark = 89

18/06/12

PAW de Diseo a Implementacin

45

Code Example
public class Module { private Vector registrations; public void enrol(Student st) { registrations.addElement( new Registration(st) ); } Maintain the link ... Pass the to Registration } Student to Registration. class Registration { private Student student; private int mark; Registration(Student st) { student = st; mark = 0; } ... }
18/06/12 PAW de Diseo a Implementacin

Registration keeps track of the Student reference.

46

Summary
n n

Basic Implementation Steps Implementing Class:


q

Class Association:
n n n n

Navigation direction Multiplicity constraint Qualified associations Association classes

18/06/12

PAW de Diseo a Implementacin

47

Reading Suggestions
n n

Chapter 8 of [Bimlesh, Andrei, Soo; 2007] Chapter 13 of [Priestley; 2004]

18/06/12

PAW de Diseo a Implementacin

48

You might also like