0% found this document useful (0 votes)
4 views42 pages

Mapping UML Models to Java Code

gedtion d'en(treprise

Uploaded by

ulrichlybawo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views42 pages

Mapping UML Models to Java Code

gedtion d'en(treprise

Uploaded by

ulrichlybawo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Maps Model to Code

Object Modelling and Programming Course


Reference: Bernd Bruegge & Allen H. Dutoit. Object-Oriented Software
Engineering using UML, Patterns and Java
State of the Art:
Model-based Software Engineering
• The Vision
• During object design we build an object design model that realizes the use
case model and it is the basis for implementation (model-driven design)
• The Reality
• Working on the object design model involves many activities that are error
prone
• Examples:
• A new parameter must be added to an operation. Because of time pressure it is added
to the source code, but not to the object model
• Additional attributes are added to an entity object, but the database table is not updated
(as a result, the new attributes are not persistent).

Lesson 3: Mapping Model to Code 2


Other Object Design Activities
• Programming languages do not support the concept of a UML association
• The associations of the object model must be transformed into collections of object
references
• Many programming languages do not support contracts (invariants, pre
and post conditions)
• Developers must therefore manually transform contract specification into source
code for detecting and handling contract violations
• The client changes the requirements during object design
• The developer must change the interface specification of the involved classes
• All these object design activities cause problems, because they need to be
done manually.
Lesson 3: Mapping Model to Code 3
Spaces and transformations
• Let us get a handle on these problems
• To do this we distinguish two kinds of spaces
• the model space and the source code space
• and 4 different types of transformations
• Model transformation,
• Forward engineering,
• Reverse engineering,
• Refactoring.

Lesson 3: Mapping Model to Code 4


4 Different Types of Transformations
Program
(in Java)
Yet Another
System Model
Another
System Model Forward
engineering

Refactoring
Model
transformation

Reverse Another
engineering Program
System Model
(in UML)
Model space Source code space

Lesson 3: Mapping Model to Code 5


Model Transformation Example
Object design model before transformation:

LeagueOwner Advertiser Player


+email:Address +email:Address +email:Address

Object design model after transformation:

User
+email:Address

LeagueOwner Advertiser Player


Lesson 3: Mapping Model to Code 6
4 Different Types of Transformations
Program
(in Java)
Yet Another
System Model
Another
System Model Forward
engineering

Refactoring
Model
transformation

Reverse Another
engineering Program
System Model
(in UML)
Model space Source code space
Lesson 3: Mapping Model to Code 7
Refactoring Example: Pull Up Field
public class Player { public class User {
private String email; private String email;
//... }
} public class Player extends User {
public class LeagueOwner { //...
private String eMail;
}
//...
} public class LeagueOwner extends User {
public class Advertiser { //...
private String email_address; }
//...
public class Advertiser extends User {
}
//...
}

Lesson 3: Mapping Model to Code 8


Refactoring Example: Pull Up Constructor Body
public class User { public class User {
private String email; public User(String email) {
} [Link] = email;
}
}
public class Player extends User { public class Player extends User {
public Player(String email) { public Player(String email) {
super(email);
[Link] = email;
}
}
}
} public class LeagueOwner extends User {
public class LeagueOwner extends User{ public LeagueOwner(String email) {
public LeagueOwner(String email) { super(email);
[Link] = email; }
} }
} public class Advertiser extends User {
public class Advertiser extendsUser{ public Advertiser(String email) {
public Advertiser(String email) { super(email);
[Link] = email; }
}
}
}

Lesson 3: Mapping Model to Code 9


4 Different Types of Transformations
Program
(in Java)
Yet Another
System Model
Another
System Model Forward
engineering

Refactoring
Model
transformation

Reverse Another
engineering Program
System Model
(in UML)
Model space Source code space
Lesson 3: Mapping Model to Code 10
Forward Engineering Example
Object design model before transformation:
User LeagueOwner
-email:String -maxNumLeagues:int
+getEmail():String +getMaxNumLeagues():int
+setEmail(e:String) +setMaxNumLeagues(n:int)
+notify(msg:String)

Source code after transformation:


public class User { public class LeagueOwner extends User {
private String email; private int maxNumLeagues;
public String getEmail() {
public int getMaxNumLeagues() {
return email;
return maxNumLeagues;
}
public void setEmail(String value){ }
email = value; public void setMaxNumLeagues
} (int value) {
public void notify(String msg) {
maxNumLeagues = value;
// ....
}
}
Lesson 3: Mapping Model
} to Code 11
}
More Examples of Model Transformations
and Forward Engineering
• Model Transformations
• Goal: Optimizing the object design model
• Collapsing objects
• Delaying expensive computations
• Forward Engineering
• Goal: Implementing the object design model in a programming language
• Mapping inheritance
• Mapping associations
• Mapping contracts to exceptions
• Mapping object models to tables

Lesson 3: Mapping Model to Code 12


Collapsing Objects
Object design model before transformation:

Person SocialSecurity
number:String

Object design model after transformation:

Person
SSN:String

Turning an object into an attribute of another object is usually


done, if the object does not have any interesting dynamic behavior
(only get and set operations).
Lesson 3: Mapping Model to Code 13
Examples of Model Transformations and
Forward Engineering
• Model Transformations
• Goal: Optimizing the object design model
• Collapsing objects
• Delaying expensive computations
• Forward Engineering
• Goal: Implementing the object design model in a programming language
• Mapping inheritance
• Mapping associations
• Mapping contracts to exceptions
• Mapping object models to tables

Lesson 3: Mapping Model to Code 14


Delaying expensive computations
Object design model before transformation:
Image
filename:String
data:byte[]
paint()

Object design model after transformation:


Image
Proxy Pattern!
filename:String
paint()

image
ImageProxy RealImage
1 0..1
filename:String data:byte[]
paint() paint()
Lesson 3: Mapping Model to Code 15
Examples of Model Transformations and
Forward Engineering
• Model Transformations
• Goal: Optimizing the object design model
• Collapsing objects
• Delaying expensive computations
• Forward Engineering
• Goal: Implementing the object design model in a programming language
• Mapping inheritance
• Mapping associations
• Mapping contracts to exceptions
• Mapping object models to tables

Lesson 3: Mapping Model to Code 16


Forward Engineering: Mapping a UML Model
into Source Code
• Goal: We have a UML-Model with inheritance. We want to translate it into
source code
• Question: Which mechanisms in the programming language can be used?
• Let’s focus on Java
• Java provides the following mechanisms:
• Overriding of methods (default in Java)
• Final classes
• Final methods
• Abstract methods
• Abstract classes
• Interfaces
Lesson 3: Mapping Model to Code 17
Realizing Inheritance in Java
• Realization of specialization and generalization
• Definition of subclasses
• Java keyword: extends
• Realization of simple inheritance
• Overriding of methods is not allowed
• Java keyword: final
• Realization of implementation inheritance
• No keyword necessary:
• Overriding of methods is default in Java
• Realization of specification inheritance
• Specification of an interface
• Java keywords: abstract, interface

Lesson 3: Mapping Model to Code 18


Examples of Model Transformations and
Forward Engineering
• Model Transformations
• Goal: Optimizing the object design model
✓ Collapsing objects
✓ Delaying expensive computations
• Forward Engineering
• Goal: Implementing the object design model in a programming language
✓Mapping inheritance
• Mapping associations
• Mapping contracts to exceptions
• Mapping object models to tables

Lesson 3: Mapping Model to Code 19


Mapping Associations
1. Unidirectional one-to-one association
2. Bidirectional one-to-one association
3. Bidirectional one-to-many association
4. Bidirectional many-to-many association
5. Bidirectional qualified association.

Lesson 3: Mapping Model to Code 20


Unidirectional one-to-one association
Object design model before transformation:
1 1
Advertiser Account

Source code after transformation:


public class Advertiser {
private Account account;
public Advertiser() {
account = new Account();
}
public Account getAccount() {
return account;
}
}

Lesson 3: Mapping Model to Code 21


Bidirectional one-to-one association
Object design model before transformation:
Advertiser 1 1
Account

Source code after transformation:


public class Advertiser { public class Account {
/* account is initialized /* owner is initialized
* in the constructor and never * in the constructor and
* modified. */ * never modified. */
private Account account;
private Advertiser owner;
public Advertiser() {
public Account(owner:Advertiser) {
account = new Account(this);
[Link] = owner;
}
}
public Account getAccount() {
return account; public Advertiser getOwner() {
} return owner;
} }
}

Lesson 3: Mapping Model to Code 22


Bidirectional one-to-many association
Object design model before transformation:
1 *
Advertiser Account

Source code after transformation:


public class Advertiser { public class Account {
private Set accounts; private Advertiser owner;
public Advertiser() { public void setOwner(Advertiser newOwner) {
accounts = new HashSet(); if (owner != newOwner) {
}
Advertiser old = owner;
public void addAccount(Account a) {
owner = newOwner;
[Link](a);
if (newOwner != null)
[Link](this);
[Link](this);
}
if (oldOwner != null)
public void removeAccount(Account a) {
[Link](this);
[Link](a);
}
[Link](null);
}
}
} }

Lesson 3: Mapping Model to Code 23


Bidirectional many-to-many association
Object design model before transformation
* {ordered} *
Tournament Player

Source code after transformation


public class Tournament { public class Player {
private List players; private List tournaments;
public Tournament() { public Player() {
players = new ArrayList(); tournaments = new ArrayList();
} }
public void addPlayer(Player p) { public void addTournament(Tournament
t) {
if (![Link](p)) { if (![Link](t)) {
[Link](p); [Link](t);
[Link](this); [Link](this);
} }
} }
} }

Lesson 3: Mapping Model to Code 24


Bidirectional qualified association
Object design model before model transformation
* *
League Player
nickName

Object design model after model transformation


* 0..1
League nickName Player

Source code after forward engineering (see next slide)

Lesson 3: Mapping Model to Code 25


Bidirectional qualified association cntd.
Object design model before forward engineering
* 0..1
League nickName Player

Source code after forward engineering


public class League { public class Player {

private Map players; private Map leagues;


public void addPlayer public void addLeague
(String nickName, Player p) {
(String nickName, League l) {
if
(![Link](nickName)) { if (![Link](l)) {
[Link](nickName, p); [Link](l, nickName);
[Link](nickName, this); [Link](nickName, this);
} }
} }
} }
Lesson 3: Mapping Model to Code 26
Examples of Model Transformations and
Forward Engineering
• Model Transformations
• Goal: Optimizing the object design model
✓ Collapsing objects
✓ Delaying expensive computations
• Forward Engineering
• Goal: Implementing the object design model in a programming language
✓Mapping inheritance
✓Mapping associations
• Mapping contracts to exceptions
• Mapping object models to tables

Lesson 3: Mapping Model to Code 27


Implementing Contract Violations
• Many object-oriented languages do not have built-in support for contracts
• However, if they support exceptions, we can use their exception
mechanisms for signaling and handling contract violations
• 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
• UML model
• In this case acceptPlayer() in TournamentControl should throw an exception of type
KnownPlayer
• Java Source code.

Lesson 3: Mapping Model to Code 28


UML Model for Contract Violation Example
TournamentForm
1
1
+applyForTournament() TournamentControl

* +selectSponsors(advertisers):List *
+advertizeTournament()
+acceptPlayer(p)
+announceTournament()
+isPlayerOverbooked():boolean
1

1
Tournament
-maNumPlayers:String
* +start:Date *
* * players +end:Date sponsors * *
Player +acceptPlayer(p) Advertiser
+removePlayer(p)
* +isPlayerAccepted(p)
matches *
matches
Match
*
+start:Date
+status:MatchStatus
+playMove(p,m)
+getScore():Map
Lesson 3: Mapping Model to Code 29
TournamentForm
1
1
+applyForTournament() TournamentControl

Implementation in Java * +selectSponsors(advertisers):List


+advertizeTournament()
+acceptPlayer(p)
+announceTournament()
+isPlayerOverbooked():boolean
1
*

1
Tournament
-maNumPlayers:String
* +start:Date *
* * players +end:Date sponsors* *
Player +acceptPlayer(p) Advertiser
+removePlayer(p)
* +isPlayerAccepted(p)
matches*
matches
Match
*
+start:Date
+status:MatchStatus
+playMove(p,m)
+getScore():Map
public class TournamentForm {
private TournamentControl control;
private ArrayList players;
public void processPlayerApplications() {
for (Iteration i = [Link](); [Link]();) {
try {
[Link]((Player)[Link]());
}
catch (KnownPlayerException e) {
// If exception was caught, log it to console
[Link]([Link]());
}
}
}
} Lesson 3: Mapping Model to Code 30
The try-throw-catch Mechanism in Java
public class TournamentControl {
private Tournament tournament;
public void addPlayer(Player p) throws KnownPlayerException {
if ([Link](p)) {
throw new KnownPlayerException(p);
}
//... Normal addPlayer behavior
}
}
public class TournamentForm {
private TournamentControl control;
private ArrayList players;
public void processPlayerApplications() {
for (Iteration i = [Link](); [Link]();) {
try {
[Link]((Player)[Link]());
}
catch (KnownPlayerException e) {
// If exception was caught, log it to console
[Link]([Link]());
}
}
}
} Lesson 3: Mapping Model to Code 31
Implementing a Contract
• Check each precondition:
• Before the beginning of the method with a test to check the precondition for that
method
• Raise an exception if the precondition evaluates to false
• Check each postcondition:
• At the end of the method write a test to check the postcondition
• Raise an exception if the postcondition evaluates to false. If more than one postcondition is
not satisfied, raise an exception only for the first violation.
• Check each invariant:
• Check invariants at the same time when checking preconditions and when checking
postconditions
• Deal with inheritance:
• Add the checking code for preconditions and postconditions also into methods that
can be called from the class.

Lesson 3: Mapping Model to Code 33


A complete implementation of the
[Link]() contract
«invariant»
getMaxNumPlayers() > 0

Tournament
«precondition»
!isPlayerAccepted(p) -maxNumPlayers: int
+getNumPlayers():int
+getMaxNumPlayers():int
+isPlayerAccepted(p:Player):boolean
+addPlayer(p:Player)

«precondition» «postcondition»
getNumPlayers() < isPlayerAccepted(p)
getMaxNumPlayers()

Lesson 3: Mapping Model to Code 34


Heuristics: Mapping Contracts to Exceptions
• Executing checking code slows down your program
• If it is too slow, omit the checking code for private and protected methods
• If it is still too slow, focus on components with the longest life
• Omit checking code for postconditions and invariants for all other components.

Lesson 3: Mapping Model to Code 35


Heuristics for Transformations
• For any given transformation always use the same tool
• Keep the contracts in the source code, not in the object design model
• Use the same names for the same objects
• Have a style guide for transformations (Martin Fowler)

Lesson 3: Mapping Model to Code 36


Object Design Areas
1. Service specification
• Describes precisely each class interface
2. Component selection
• Identify off-the-shelf components and additional solution objects
3. Object model restructuring
• Transforms the object design model to improve its understandability and
extensibility
4. Object model optimization
• Transforms the object design model to address performance criteria such as
response time or memory utilization.

Lesson 3: Mapping Model to Code 37


Design Optimizations
• Design optimizations are an important part of the object design
phase:
• The requirements analysis model is semantically correct but often too
inefficient if directly implemented.
• Optimization activities during object design:
1. Add redundant associations to minimize access cost
2. Rearrange computations for greater efficiency
3. Store derived attributes to save computation time
• As an object designer you must strike a balance between efficiency
and clarity.
• Optimizations will make your models more obscure

Lesson 3: Mapping Model to Code 38


Design Optimization Activities
1. Add redundant associations:
• What are the most frequent operations? ( Sensor data lookup?)
• How often is the operation called? (30 times a month, every 50 milliseconds)
2. Rearrange execution order
• Eliminate dead paths as early as possible (Use knowledge of distributions,
frequency of path traversals)
• Narrow search as soon as possible
• Check if execution order of loop should be reversed
3. Turn classes into attributes

Lesson 3: Mapping Model to Code 39


Implement application domain classes
• To collapse or not collapse: Attribute or association?
• Object design choices:
• Implement entity as embedded attribute
• Implement entity as separate class with associations to other classes
• Associations are more flexible than attributes but often introduce
unnecessary indirection

Lesson 3: Mapping Model to Code 40


Optimization Activities: Collapsing Objects
Matrikelnumber
Student ID:String

Student
Collapse or not to
Matrikelnumber:String
collapse?

Collapse a class into an attribute if the only operations defined


on the attributes are Set() and Get().
Lesson 3: Mapping Model to Code 41
Design Optimizations (continued)
Store derived attributes
• Example: Define new classes to store information locally (database cache)
• Problem with derived attributes:
• Derived attributes must be updated when base values change.
• There are 3 ways to deal with the update problem:
• Explicit code: Implementor determines affected derived attributes (push)
• Periodic computation: Recompute derived attribute occasionally (pull)
• Active value: An attribute can designate set of dependent values which are automatically
updated when active value is changed (notification, data trigger)

Lesson 3: Mapping Model to Code 42


Summary
• Four mapping concepts:
• Model transformation
• Forward engineering
• Refactoring
• Reverse engineering
• Model transformation and forward engineering techniques:
• Optiziming the class model
• Mapping associations to collections
• Mapping contracts to exceptions
• Mapping class model to storage schemas

Lesson 3: Mapping Model to Code 43

You might also like