Object-Oriented Software Engineering
Using UML, Patterns, and Java Chapter 10,
Mapping Models to Code
Overview
Operations on the object model:
Optimizations to address performance requirements
Implementation of class model components:
Realization of associations
Realization of operation contracts Self reading
Realizing entity objects based on selected storage strategy
Mapping the class model to a storage schema
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 2
Characteristics of Object Design Activities
Developers perform transformations to the object model to
improve its modularity and performance.
Developers transform the associations of the object model into
collections of object references, because programming
languages do not support the concept of association.
If the programming language does not support contracts, the
developer needs to write code for detecting and handling
contract violations. Self reading In C++? In Java?
Developers often revise the interface specification to
accommodate new requirements from the client.
All these activities are intellectually not challenging
However, they have a repetitive and mechanical flavor that makes
them error prone.
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 3
State of the Art of Model-based Software Engineering
The Vision
During object design we would like to implement a system that realizes
the use cases specified during requirements elicitation and system
design. Recall our discussion
The Reality
Different developers usually handle contract violations differently.
Undocumented parameters are often added to the API to address
a requirement change.
Additional attributes are usually added to the object model, but are
not handled by the persistent data management system, possibly
because of a miscommunication. And lack of traceability?
Many improvised code changes and workarounds are made ad hoc,
which eventually leads to a severe degradation of the system.
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 4
Model transformations
Forward
engineering
Refactoring
Model
transformation
Reverse
engineering
Model space Source code space
1-1 mapping?
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 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
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 6
Refactoring Example: Pull Up Field
public class User {
private String email;
}
public class Player { public class Player
private String email; extends User {
//... //...
} }
public class LeagueOwner { public class LeagueOwner extends
private String eMail; User {
//... //...
} }
public class Advertiser {
public class Advertiser extends
private String User {
email_address;
//...
//...
}
}
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 7
Refactoring Example: Pull Up Constructor Body
public class User {
public class User {
public User(String email) {
private String email; [Link] = email;
} }
}
public class Player extends
User {
public Player(String email) public class Player extends
{ User {
[Link] = email; public Player(String email){
} super(email);
} }
public class LeagueOwner }
extends User{ public class LeagueOwner
public LeagueOwner(String extends User {
email) { public LeagueOwner(String
[Link] = email; email) {
} super(email);
} Bernd Bruegge & Allen H. Dutoit
}
Object-Oriented Software Engineering: Using UML, Patterns, and Java 8
Other Mapping Activities
Optimizing the Object Design Model
Collapsing objects
Delaying expensive computations
Mapping Associations
Mapping Contracts to Exceptions Self reading
Mapping Object Models to Tables
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 9
Collapsing an object without interesting behavior
Object design model before transformation
Person SocialSecurity
number:String
Object design model after transformation ?
Person
SSN:String
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 10
Self reading
Delaying expensive computations
Object design model before transformation
Image
filename:String
data:byte[]
paint()
Object design model after transformation
Image
filename:String
? paint()
A good model?
Proxy Pattern
image
ImageProxy RealImage
1 0..1
filename:String data:byte[]
paint() paint()
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 11
Other Mapping Activities
Optimizing the Object Design Model
Mapping Associations
Mapping Contracts to Exceptions
Mapping Object Models to Tables
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 12
Realization of a unidirectional, one-to-one association
Object design model before transformation Which direction?
1 1
Advertiser Account
Role name?
Source code after transformation
public class Advertiser {
private Account account;
public Advertiser() {
account = new Account();
}
public Account getAccount() {
return account;
}
}
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 13
Bidirectional one-to-one association
Object design model before transformation
Advertiser 1 1
Account
Source code after transformation Role name?
public class Advertiser { public class Account {
/* The account field is initialized /* The owner field is initialized
* in the constructor and never * during 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() { public Advertiser getOwner() {
return account; return owner;
} }
} }
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 14
Bidirectional, one-to-many association
Object design model before transformation
1 *
Advertiser Account
Source code after transformation constructor?
public class Advertiser { public class Account {
private Set accounts; private Advertiser owner;
public void setOwner(Advertiser
public 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); }
} }
}
complete?
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 15
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;
/* ordered collection = sequence */
public Tournament() { public Player() {
players = new ArrayList(); tournaments = new ArrayList();
} /* implements List */ }
public void addPlayer(Player p) { public void addTournament(Tournament t)
{
if () { if () {
[Link](p); [Link](t);
[Link](this); [Link](this);
} }
} }
} }
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 16
Transformation of an association class
Object design model before transformation
Statistics
+getAverageStat(name)
+getTotalStat(name)
+updateStats(match)
Tournament Player
* *
What’s the change?
Object design model after transformation: 1 class and two binary associations
Statistics
+getAverageStat(name)
+getTotalStat(name)
+updateStats(match)
1 1
Tournament Player
* *
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 17
Other Mapping Activities
Optimizing the Object Design Model
Mapping Associations
Mapping Contracts to Exceptions Self reading
Mapping Object Models to Tables
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 18
Mapping an object model to a relational database
UML object models can be mapped to relational databases:
Some degradation occurs because all UML constructs must be
mapped to a single relational database construct - the table.
Mapping of classes, attributes and associations 1-1 mapping?
Each class is mapped to a table
Each class attribute is mapped onto a column in the table
An instance of a class represents a row in the table
A many-to-many association is mapped into its own table
A one-to-many association is implemented as buried foreign key
Methods are not mapped
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 19
Mapping the User class to a database table
User
+firstName:String
+login:String
+email:String
User table
id:long firstName:text[25] login:text[8] email:text[32]
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 20
Primary and Foreign Keys
Any set of attributes that could be used to uniquely identify any
data record in a relational table is called a candidate key.
The actual candidate key that is used in the application to
identify the records is called the primary key.
The primary key of a table is a set of attributes whose values
uniquely identify the data records in the table.
A foreign key is an attribute (or a set of attributes) that
references the primary key of another table.
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 21
Example for Primary and Foreign Keys
Primary key
User table
firstName login email
“alice” “am384” “am384@[Link]”
“john” “js289” “john@[Link]”
“bob” “bd” “bobd@[Link]”
Candidate key Candidate key
League table name login
“tictactoeNovice” “am384”
“tictactoeExpert” “am384”
“chessNovice” “js289”
Foreign key referencing User table
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 22
Buried Association
Associations with multiplicity “one” can be implemented using
a foreign key. Because the association vanishes in the table,
we call this a buried association.
For one-to-many associations we add the foreign key to the
table representing the class on the “many” end.
For all other associations we can select either class at the end
of the association.
1 *
LeagueOwner League
LeagueOwner table League table
id:long ... id:long ... owner:long
1-1 mapping?
Bernd Bruegge & Allen H. Dutoit What about
Object-Oriented the 1
Software Engineering: Using (*) side?
UML, Patterns, and Java 23
Another Example for Buried Association
Portfolio
Transaction *
portfolioID
transactionID ...
Transaction Table Portfolio Table
transactionID portfolioID portfolioID ...
Foreign Key
1-1 mapping?
Bernd Bruegge & Allen H. Dutoit What about
Object-Oriented the 1
Software Engineering: Using (*) side?
UML, Patterns, and Java 24
Mapping Many-To-Many Associations
In this case we need a separate table for the association
City * Serves Airport
*
airportCode
cityName airportName Separate table for
the association “Serves”
Primary Key
City Table Airport Table Serves Table
airportCode airportName cityName airportCode
cityName IAH Intercontinental Houston IAH
Houston HOU Hobby Houston HOU
Albany ALB Albany County Albany ALB
Munich MUC Munich Airport Munich MUC
Hamburg HAM Hamburg Airport Hamburg HAM
Bernd Bruegge & Allen H. Dutoit What are these?
Object-Oriented Software Engineering: Using UML, Patterns, and Java 25
Another Many-to-Many Association Mapping
We need the Tournament/Player association as a separate table
Tournament * * Player
Tournament table Player table
TournamentPlayerAssociation
id name ... id name ...
table
23 novice 56 alice
tournament player
24 expert 79 john
23 56
23 79
Bernd Bruegge & Allen H. Dutoit What about
Object-Oriented the Using
Software Engineering: keys – primary
UML, Patterns, and Java & foreign?
26
Realizing Inheritance
Relational databases do not support inheritance
Two possibilities to map an inheritance association to a
database schema
With a separate table (”vertical mapping”)
The attributes of the superclass and the subclasses are mapped
to different tables
By duplicating columns (”horizontal mapping”) /* flattening
There is no table for the superclass
Each subclass is mapped to a table containing the attributes of
the subclass and the attributes of the superclass
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 27
Realizing inheritance with a separate table
(”vertical mapping”)
User
name
LeagueOwner Player
maxNumLeagues credits
User table
id name ... role
56 zoe LeagueOwner
79 john Player
LeagueOwner table Player table
id maxNumLeagues ... id credits ...
56 12 79 126
What should
Bernd Bruegge & Allen H. Dutoit be Software
Object-Oriented done toUsingretrieve
Engineering: UML, Patterns, and Java player info?
28
Realizing inheritance by duplicating columns
(”horizontal mapping”)
User
name
LeagueOwner Player
maxNumLeagues credits
LeagueOwner table Player table
id name maxNumLeagues ... id name credits ...
56 zoe 12 79 john 126
What should
Bernd Bruegge be done when
& Allen H. Dutoit the
Object-Oriented Software“name” ofPatterns,
Engineering: Using UML, a and user
Java changes? 29
Comparison: Separate Tables vs Duplicated Columns
The trade-off is between modifiability and response time
How likely is a change of the superclass? If high, which one?
What are the performance requirements for queries?
Separate table mapping(”vertical mapping”)
We can add attributes to the superclass easily by adding a column
to the superclass table
Searching for the attributes of an object requires a join operation.
(”horizontal
Duplicated columns mapping”)
e.g., a hierachy
Modifying the database schema is more complex and error-prone
Individual objects are not fragmented across a number of tables,
resulting in faster queries
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 30
Heuristics for Transformations
For a given transformation use the same tool
If you are using a CASE tool to map associations to code, use the tool
to change association multiplicities.
Keep the contracts in the source code, not in the object design
model
By keeping the specification as a source code comment, they are more
likely to be updated when the source code changes.
Use the same names for the same objects
If the name is changed in the model, change the name in the code and
or in the database schema.
Provides traceability among the models
Have a style guide for transformations
By making transformations explicit in a manual , all developers
can apply the transformation in the same way.
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 31
Summary
Undisciplined changes => degradation of the system model
Four mapping concepts were introduced
Model transformation improves the compliance of the object design model with
a design goal
Forward engineering improves the consistency of the code with respect to the
object design model
Refactoring improves the readability or modifiability of the code
Reverse engineering attempts to discover the design from the code.
We reviewed model transformation and forward engineering
techniques:
Optiziming the class model
Mapping associations to collections
Mapping contracts to exceptions
Mapping class model to storage schemas
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 32