Association Clases

9
1 Ma ppin g Models t o Code Lecture #12 Software Engineering and Project Management Instructed by Steven Choy on Jan 22, 2007 2 Where are we he ading NOW? Requirement Elicitation Requirement Analysis System Design Object Design Implementation (Coding) Testing * Deployment * Maintenance * - not listed in textbook 3  O v  e r  v i    e w Source: Object- Oriented Software Engineering by Bruegge and Dutoit 4 Mappin g Con ce pt s Source code space Forward engineering Refactoring Reverse engineering Model space Model transformation Source: Object-Oriented Software Engineering by Bruegge and Dutoit

Transcript of Association Clases

Page 1: Association Clases

7/31/2019 Association Clases

http://slidepdf.com/reader/full/association-clases 1/9

1

Mapp in g Mode ls

t o Cod eLecture #12

Software Engineering and

Project Management

Instructed by Steven Choy on Jan 22, 2007

2

W here are w e head ing NOW ?

Requ i remen tE l ic i ta t ion

Requ i remen tAna lys is

SystemDesign

ObjectDesign

I m p l e m e n t a t i o n

(Cod ing)

Test ing

* Deployment

* Maintenance

* - not listed in textbook

3

 Ov er  vi    ew

Source: Object-Oriented SoftwareEngineering byBruegge and Dutoit

4

Mappin g Con cept s

Source code space

Forward engineering

Refactoring

Reverse engineering

Model space

Model

transformation

Source: Object-Oriented Software Engineering by Bruegge and Dutoit

Page 2: Association Clases

7/31/2019 Association Clases

http://slidepdf.com/reader/full/association-clases 2/9

5

Model Trans fo rm a t i onObject design model before transformation

Object design model after

transformation:

Advertiser

+email:Address

Player

+email:Address

LeagueOwner

+email:Address

PlayerAdvertiserLeagueOwner

User

+email:Address

Model transformations work on objectmodels. Eg. Converting an attribute toa class

Refac to r ing

public class Player {

private String email;

//...

}

public class LeagueOwner {

private String eMail;

//...

}

public class Advertiser {

private String email_address;

//...

}

public class User {

private String email;

}

public class Player extends

User {

//...

}

public class LeagueOwnerextends User {

//...

}

public class Advertiser extendsUser {

//...

}

Operate on source code, ie. Improving a singleaspect of the system without changing itsfunctionality

Forw ard Eng in eer i ng

public class User {

private String email;

public String getEmail() {

return email;

}

public void setEmail(String value){

email = value;

}

public void notify(String msg) {

// ....

}

/* Other methods omitted */

}

public class LeagueOwner extends User {

private int maxNumLeagues;

public int getMaxNumLeagues() {

return maxNumLeagues;

}

public void setMaxNumLeagues

(int value) {

maxNumLeagues = value;

}

/* Other methods omitted */

}

User LeagueOwner

+maxNumLeagues:int

Object design model before transformation

Source code after transformation

+email:String+notify(msg:String)

Produce a code template that

corresponds to an object model.

8

Rever se Eng in eer in g

Applied to a set of source code elements andresults in a set of model elements

Recreate the model for an existing system

Page 3: Association Clases

7/31/2019 Association Clases

http://slidepdf.com/reader/full/association-clases 3/9

9

Mapp ing m ode l s t o code :

Overv iew on Mapp ing Assoc ia t i on s

10

Unid i rec t iona l One- to -OneAsso icat ion

public class Student {

private Account account;

public Student() {

account = new Account();

}

public Account getAccount() {

return account;

}

}

public class Account {

public Account() {

}

}

11

Bid i rec t iona l One- to-OneAssoc iat ion

public class Student {

private Account account;

public Student() {

account = new Account(t h i s);

}

public Account getAccount() {

return account;

}

}

public class Account {

private Student owner;

public Account(Student student) {

owner = student;

}

public Student getOwner() {

return student;

}

}

12

One- t o -Many Assoc ia t ion

public class Student {

private Set accounts;

public Student() {

accounts = new HashSet();

}

public void addAccount(Accountaccount) {

accounts.add(account);

}

public Account removeAccount(Accountaccount) {

accounts.remove(account);

}

}

public class Account {

public Account() {

}

}

Page 4: Association Clases

7/31/2019 Association Clases

http://slidepdf.com/reader/full/association-clases 4/9

13

Many - t o -ManyAssoc ia t ion

public class Student {

private List courses;

public Student() {

courses = new ArrayList();

}

public void addCourse(Course course) {

if (!courses.contains(course)) {

courses.add(course);course.addStudent(this);

}

}

}

public class Course {

private List students;

public Course() {

students = new ArrayList();

}

public void addStudent(Student student){

if (!students.contains(student)) {

students.add(student);

student.addCourse(this);

}

}

}14

Qual i f ied Assoc ia t ion s

public class Student {

private Map accounts;

public Student() {

accounts = new HashMap();

}

public void addAccount(String accountId,Account account) {

accounts.put(accountId, account);

}

public Account getAccount(StringaccountId) {

return(Account)accounts.get(acccountId);

}

}

public class Account {

public Account() {

}

}

15

Mapp ing Act i v i t i es

Optimizing the Object Design Model

Mapping Associations Mapping Contracts to Exceptions

Mapping Object Models to Tables

16

Opt im iz ing the Ob jec t Design Mode l :Co l l apsing an ob jec t w i t hou t i n t e r es t i ng behav io r

Person SocialSecuritynumber:String

Person

SSN:String

Object design model before transformation

Object design model after transformation

Page 5: Association Clases

7/31/2019 Association Clases

http://slidepdf.com/reader/full/association-clases 5/9

17

Opt im iz ing the Ob jec t Des ign Mode l :De lay ing expens i ve compu t a t i ons

Object design model before transformation

Object design model after transformation

Image

filename:String

paint()data:byte[]

Image

filename:String

RealImage

data:byte[]

ImageProxy

filename:String

image

1 0..1

paint()

paint() paint()

Loading the real image can beexpensive. ImageProxy servescalls like width() and height()and loads the real image filewhen it needs to be drawn ordisplayed

Real iza t ion o f a un id i rec t ion a l , one- to -one assoc iat ion

AccountAdvertiser11

Object design model before transformation

Source code after transformation

public class Advertiser {

private Account account;

public Advertiser() {

account = new Account();

}public Account getAccount() {

return account;

}

}

Bid i rec t i ona l one- t o -on e associa t i on

public class Advertiser {

/* The account field isinitialized

* in the constructor and never

* modified. */

private Account account;

public Advertiser() {

account = new Account(this);

}

public Account getAccount() {

return account;

AccountAdvertiser11

Object design model before transformation

Source code after transformation

public class Account {

/* The owner field is initialized

* during the constructor and

* never modified. */

private Advertiser owner;

public Account(owner:Advertiser){

this.owner = owner;

}

public Advertiser getOwner() {

return owner;

}

}

Bid i rec t i ona l , one- t o -m any assoc ia t i on

public class Advertiser {

private Set accounts;public Advertiser() {

accounts = new HashSet();

}

public void addAccount(Account a){

accounts.add(a);

a.setOwner(this);

}

public void removeAccount(Account

a) {accounts.remove(a);

a.setOwner(null);

}

}

public class Account {

private Advertiser owner;

public void setOwner(AdvertisernewOwner) {

if (owner != newOwner) {

Advertiser old = owner;

owner = newOwner;

if (newOwner != null)

newOwner.addAccount(this);

if (oldOwner != null)

old.removeAccount(this);

}

}

}

Advertiser Account1 *

Object design model before transformation

Page 6: Association Clases

7/31/2019 Association Clases

http://slidepdf.com/reader/full/association-clases 6/9

Bid i rec t i ona l , many- to -many assoc ia t i on

public class Tournament {private List players;

public Tournament() {

players = new ArrayList();

}

public void addPlayer(Player p) {

if (!players.contains(p)) {

players.add(p);

p.addTournament(this);

}

}}

public class Player {

private List tournaments;

public Player() {

tournaments = new ArrayList();

}

public void addTournament(Tournament t) {

if (!tournaments.contains(t)) {

tournaments.add(t);

t.addPlayer(this);

}

}

}

Tournament Player* *{ordered}

Object design model before transformation

22

Bid i rec t i ona l qu a l i f i ed assoc iat i on

Object design model after transformation

PlayernickName0..1*League

Player**

Object design model before transformation

League

nickName

23

Bid i rec t i ona l qua l i f i ed associa t i on ( con t ’d )

public class League {

private Map players;

Public League(){

players = new HashMap();

}

public void addPlayer(String nickName, Player p) {

if (!players.containsKey(nickName)) {

players.put(nickName, p);

p.addLeague(nickName, this);

}

}

}

public class Player {

private Map leagues;

public void addLeague(String nickName, League l) {

if (!leagues.containsKey(l)) {

leagues.put(l, nickName);

l.addPlayer(nickName, this);

}

}

}

Source code after transformation

24

Trans fo rm at ion o f an assoc iat i on c lass

Tournament Player* *

Object design model before transformation

Object design model after transformation: 1 class and two binary associations

Statistics

+getAverageStat(name)+getTotalStat(name)+updateStats(match)

Tournament Player* *

1 1

Statistics

+getAverageStat(name)+getTotalStat(name)

+updateStats(match)

Page 7: Association Clases

7/31/2019 Association Clases

http://slidepdf.com/reader/full/association-clases 7/9

25

Excep t ion s as bu i l d ing b locks fo rcon t rac t v i o l a t i ons

Many object-oriented languages, including Java, donot include built-in support for contracts.

However, we can use their exception mechanisms asbuilding blocks for signaling and handling contractviolations

In Java we use the try-throw-catch mechanism

Example:

Let us assume the acceptPlayer() operation of TournamentControl is invoked with a player who is

already part of the Tournament. In this case acceptPlayer() should throw an exception

of type KnownPlayer.

See source code on next slide26

The t r y - t h row -ca t ch M echan i sm i n Java

public class TournamentControl {

private Tournament tournament;

public void addPlayer(Player p) throws KnownPlayerException {

if (tournament.isPlayerAccepted(p)) {

throw new KnownPlayerException(p);

}//... Normal addPlayer behavior

}}

public class TournamentForm {

private TournamentControl control;

private ArrayList players;

public void processPlayerApplications() {// Go through all the players

for (Iteration i = players.iterator(); i.hasNext();) {

try { // Delegate to the control object.

control.acceptPlayer((Player)i.next());} catch (KnownPlayerException e) {

// If an exception was caught, log it to the console

ErrorConsole.log(e.getMessage());}

}}

}

27

I m p l em e n t i n g a co n t r a ct

For each operation in the contract, do the following

Check p r econd i t ion : Check the precondition beforethe beginning of the method with a test that raisesan exception if the precondition is false.

Check pos tcond i t ion : Check the postcondition atthe end of the method and raise an exception if thecontract is violoated. If more than one postconditionis not satisfied, raise an exception only for the firstviolation.

Check invar ian t : Check invariants at the same timeas postconditions.

Deal w i t h i nhe r i t ance: Encapsulate the checking

code for preconditions and postconditions intoseparate methods that can be called fromsubclasses.

28

M app ing an ob j ect m ode l t o are la t i on a l da tabase

UML object models can be mapped to relationaldatabases:

Some degradation occurs because all UML constructsmust be mapped to a single relational database

construct - the table. UML mappings

Each class is mapped to a table

Each class attribute is mapped onto a column in thetable

An instance of a class represents a row in the table

A many-to-many association  is mapped into its owntable

A one-to-many association  is implemented as buriedforeign key

Methods are not mapped

Page 8: Association Clases

7/31/2019 Association Clases

http://slidepdf.com/reader/full/association-clases 8/9

29

Mapp ing t he User c lass to ada tabase tab le

User

+firstName:String+login:String

+email:String

id:long firstName:text[25] login:text[8] email:text[32]

User table

30

Pr im ary and Fore ign Keys

Any set of attributes that could be used to uniquely

identify any data record in a relational table is called aca n di d at e k e y.

The actual candidate key that is used in theapplication to identify the records is called thep r i m a r y k e y .

The primary key of a table is a set of attributes whosevalues uniquely identify the data records in the table.

A f o re i gn k ey is an attribute (or a set of attributes)that references the primary key of another table.

Exam ple fo r Pr im ary and Fore ign Keys

User table

Candidate key

login email

“am384” “[email protected]

“js289” “[email protected]

firstName

“alice”

“john”

“bd” “[email protected]”“bob”

Candidate key

Primary key

League table login

“am384”

“am384”

name

“tictactoeNovice”

“tictactoeExpert”

“js289”“chessNovice”

Foreign key referencing User table

Bur ied Associa t ion

LeagueLeagueOwner *1

id:long

LeagueOwner table

... owner:long

League table

...id:long

Associations with multiplicity “one” can be implemented using aforeign key. Because the association vanishes in the table, we callthis a buried association.

For one-to-many associations we add the foreign key to the tablerepresenting the class on the “many” end.

For all other associations we can select either class at the end of the

association.

Page 9: Association Clases

7/31/2019 Association Clases

http://slidepdf.com/reader/full/association-clases 9/9

33

Real i zi ng I nhe r i t ance

Relational databases do not support inheritance

Two possibilities to map UML inheritance

relationships to a database schema With a separate table (vertical mapping)

The attributes of the superclass and the subclassesare mapped to different tables

By duplicating columns (horizontal mapping)

There is no table for the superclass

Each subclass is mapped to a table containing theattributes of the subclass and the attributes of thesuperclass

Rea li z ing i nhe r i t ance w i t h a separa t et ab l e

User table

id

56

name ...

zoe

79 john

role

LeagueOwner

Player

Player

User

LeagueOwner

maxNumLeagues credits

name

Player table

id

79

credits ...

126

id

LeagueOwner table

56

maxNumLeagues ...

12

Rea l i zing i nh er i t ance by du p l i ca t i ngc o l u m n s

Player

User

LeagueOwner

maxNumLeagues credits

name

id

LeagueOwner table

56

maxNumLeagues ...

12

name

zoe

Player table

id

79

credits ...

126

name

 john

Com par ison: Separ ate Tab les vsDup l i ca ted Co lum ns

The trade-off is between modifiability and response time

How likely is a change of the superclass?

What are the performance requirements for queries?

Separate table mapping

☺ We can add attributes to the superclass easily by addinga column to the superclass table

Searching for the attributes of an object requires a joinoperation.

Duplicated columns

Modifying the database schema is more complex and

error-prone☺ Individual objects are not fragmented across a number

of tables, resulting in faster queries