Using UML Patterns and Java ObjectOriented Software Engineering

Using UML, Patterns, and Java Object-Oriented Software Engineering Chapter 10, Mapping Models to Code

Overview ¨ ¨ Object design is situated between system design and implementation. Object design is not very well understood and if not well done, leads to a bad system implementation. In this lecture, we describe a selection of transformations to illustrate a disciplined approach to implementation to avoid system degradation. 1. Operations on the object model: t Optimizations to address performance requirements 2. Implementation of class model components: t Realization of associations t Realization of operation contracts 3. Realizing entity objects based on selected storage strategy t 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. 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. ¨ 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. Many improvised code changes and workarounds that eventually yield to the 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 Bernd Bruegge & Allen H. Dutoit Source code space Object-Oriented Software Engineering: Using UML, Patterns, and Java 5

Model Transformation Example Object design model before transformation League. Owner +email: Address Object design model after transformation: Player Advertiser +email: Address User +email: Address League. Owner Bernd Bruegge & Allen H. Dutoit Advertiser Object-Oriented Software Engineering: Using UML, Patterns, and Java Player 6

Refactoring Example: Pull Up Field public class User { private String email; } public class Player { private String email; //. . . } public class League. Owner { private String e. Mail; //. . . } public class Advertiser { private String email_address; //. . . } Bernd Bruegge & Allen H. Dutoit public class Player extends User { //. . . } public class League. Owner extends User { //. . . } public class Advertiser extends User { //. . . } Object-Oriented Software Engineering: Using UML, Patterns, and Java 7

Refactoring Example: Pull Up Constructor Body public class Player extends User { public Player(String email) { this. email = email; } } public class User { public User(String email) { this. email = email; } } public class Player extends User { public Player(String email) { super(email); } } public class League. Owner extends User{ public League. Owner(String email) { this. email = email; } } public class League. Owner extends User { public League. Owner(String email) { super(email); } } public class Advertiser extends. User{ public Advertiser(String email) { this. email = email; } } public class Advertiser extends User { public Advertiser(String email) { super(email); } } public class User { private String email; } Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 8

Forward Engineering Example Object design model before transformation League. Owner +max. Num. Leagues: int User +email: String +notify(msg: String) Source code after transformation public class User { private String email; public String get. Email() { return email; } public void set. Email(String value){ email = value; } public void notify(String msg) { //. . } /* Other methods omitted */ } Bernd Bruegge & Allen H. Dutoit public class League. Owner extends User { private int max. Num. Leagues; public int get. Max. Num. Leagues() { return max. Num. Leagues; } public void set. Max. Num. Leagues (int value) { max. Num. Leagues = value; } /* Other methods omitted */ } Object-Oriented Software Engineering: Using UML, Patterns, and Java 9

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 10

Collapsing an object without interesting behavior Object design model before transformation Person Social. Security number: String Object design model after transformation ? Person SSN: String Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 11
![Delaying expensive computations Object design model before transformation Image filename: String data: byte[] paint() Delaying expensive computations Object design model before transformation Image filename: String data: byte[] paint()](http://slidetodoc.com/presentation_image_h2/6c10e774b2ebdf762c394db4a9e65ec6/image-12.jpg)
Delaying expensive computations Object design model before transformation Image filename: String data: byte[] paint() Object design model after transformation ? Image filename: String paint() Image. Proxy filename: String paint() Bernd Bruegge & Allen H. Dutoit image 1 0. . 1 Real. Image data: byte[] paint() Object-Oriented Software Engineering: Using UML, Patterns, and Java 12

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 13

Realization of a unidirectional, one-to-one association Object design model before transformation Advertiser 1 Source code after transformation 1 Account ? public class Advertiser { private Account account; public Advertiser() { account = new Account(); } public Account get. Account() { return account; } } Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 14

Bidirectional one-to-one association Object design model before transformation 1 Advertiser 1 Account Source code after transformation public class Advertiser { /* The account field is initialized * in the constructor and never * modified. */ private Account account; public Advertiser() { account = new Account(this); } public Account get. Account() { return account; } } Bernd Bruegge & Allen H. Dutoit 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 get. Owner() { return owner; } } Object-Oriented Software Engineering: Using UML, Patterns, and Java 15

Bidirectional, one-to-many association Object design model before transformation Advertiser 1 * Account Source code after transformation public class Account { public class Advertiser { private Advertiser owner; private Set accounts; public void set. Owner(Advertiser new. Owner) public Advertiser() { { accounts = new Hash. Set(); if (owner != new. Owner) { } Advertiser old = owner; public void add. Account(Account a) { owner = new. Owner; accounts. add(a); if (new. Owner != null) a. set. Owner(this); } new. Owner. add. Account(this); public void remove. Account(Account a) if (old. Owner != null) { accounts. remove(a); old. remove. Account(this); a. set. Owner(null); } } Bernd Bruegge & Allen H. Dutoit Object-Oriented Software }Engineering: Using UML, Patterns, and Java 16

Bidirectional, many-to-many association Object design model before transformation Tournament * {ordered} * Player Source code after transformation public class Tournament { public class Player { private List players; private List tournaments; public Tournament() { public Player() { players = new Array. List(); tournaments = new Array. List(); } } public void add. Player(Player p) { public void add. Tournament(Tournament t) { if (!players. contains(p)) { if (!tournaments. contains(t)) { players. add(p); tournaments. add(t); p. add. Tournament(this); t. add. Player(this); } } } Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 17

Bidirectional qualified association Object design model before transformation League * * Player nick. Name Object design model before forward engineering League nick. Name * 0. . 1 Player Source code after forward engineering Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 18

Bidirectional qualified association (continued) Source code after forward engineering public class League { private Map players; public class Player { private Map leagues; public void add. Player (String nick. Name, Player p) { if (!players. contains. Key(nick. Name)) { players. put(nick. Name, p); p. add. League(nick. Name, this); } } } public void add. League (String nick. Name, League l) { if (!leagues. contains. Key(l)) { leagues. put(l, nick. Name); l. add. Player(nick. Name, this); } } } Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 19

Transformation of an association class Object design model before transformation Statistics +get. Average. Stat(name) +get. Total. Stat(name) +update. Stats(match) Tournament * * Player Object design model after transformation: 1 class and two binary associations Statistics +get. Average. Stat(name) +get. Total. Stat(name) +update. Stats(match) 1 1 Tournament Bernd Bruegge & Allen H. Dutoit * * Object-Oriented Software Engineering: Using UML, Patterns, and Java Player 20

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 21

Exceptions as building blocks for contract violations ¨ ¨ Many object-oriented languages, including Java do not include built-in support for contracts. However, we can use their exception mechanisms as building blocks for signaling and handling contract violations In Java we use the try-throw-catch mechanism Example: Let us assume the accept. Player() operation of Tournament. Control is invoked with a player who is already part of the Tournament. In this case accept. Player() should throw an exception of type Known. Player. See source code on next slide Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 22

The try-throw-catch Mechanism in Java public class Tournament. Control { private Tournament tournament; public void add. Player(Player p) throws Known. Player. Exception { if (tournament. is. Player. Accepted(p)) { throw new Known. Player. Exception(p); } //. . . Normal add. Player behavior } } public class Tournament. Form { private Tournament. Control control; private Array. List players; public void process. Player. Applications() { // Go through all the players for (Iteration i = players. iterator(); i. has. Next(); ) { try { // Delegate to the control object. control. accept. Player((Player)i. next()); } catch (Known. Player. Exception e) { // If an exception was caught, log it to the console Error. Console. log(e. get. Message()); } } Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 23

Implementing a contract For each operation in the contract, do the following ¨ Check precondition: Check the precondition before the beginning of the method with a test that raises an exception if the precondition is false. ¨ Check postcondition: Check the postcondition at the end of the method and raise an exception if the contract is violoated. If more than one postcondition is not satisfied, raise an exception only for the first violation. ¨ Check invariant: Check invariants at the same time as postconditions. ¨ Deal with inheritance: Encapsulate the checking code for preconditions and postconditions into separate methods that can be called from subclasses. Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 24

A complete implementation of the Tournament. add. Player() contract «invariant» get. Max. Num. Players() > 0 «precondition» !is. Player. Accepted(p) Tournament -max. Num. Players: int +get. Num. Players(): int +get. Max. Num. Players(): int +is. Player. Accepted(p: Player): boolean +add. Player(p: Player) «precondition» get. Num. Players() < get. Max. Num. Players() Bernd Bruegge & Allen H. Dutoit «postcondition» is. Player. Accepted(p) Object-Oriented Software Engineering: Using UML, Patterns, and Java 25

Heuristics for Mapping Contracts to Exceptions Be pragmatic, if you don’t have enough time. ¨ Omit checking code for postconditions and invariants. Usually redundant with the code accomplishing the functionality of the class Not likely to detect many bugs unless written by a separate tester. ¨ ¨ Omit the checking code for private and protected methods. Focus on components with the longest life Focus on Entity objects, not on boundary objects associated with the user interface. ¨ Reuse constraint checking code. Many operations have similar preconditions. Encapsulate constraint checking code into methods so that they can share the same exception classes. Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 26

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 27

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. ¨ UML mappings ¨ 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 28

Mapping the User class to a database table User +first. Name: String +login: String +email: String User table id: long first. Name: text[25] Bernd Bruegge & Allen H. Dutoit login: text[8] Object-Oriented Software Engineering: Using UML, Patterns, and Java email: text[32] 29

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 30

Example for Primary and Foreign Keys Primary key User table first. Name login email “alice” “am 384@mail. org” “john” “js 289” “john@mail. de” “bob” “bd” “bobd@mail. ch” Candidate key League table name Candidate key login “tictactoe. Novice” “am 384” “tictactoe. Expert” “am 384” “chess. Novice” “js 289” Foreign key referencing User table Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 31

Buried Association ¨ ¨ ¨ Associations with multiplicity one can be implemented using a foreign key. For one-to-many associations we add a 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. Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 32

Buried 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. ¨ League. Owner 1 * League. Owner table id: long Bernd Bruegge & Allen H. Dutoit . . . League table id: long . . . Object-Oriented Software Engineering: Using UML, Patterns, and Java owner: long 33

Another Example for Buried Association Transaction Portfolio * transaction. ID Foreign Key Transaction Table transaction. ID Bernd Bruegge & Allen H. Dutoit portfolio. ID Object-Oriented Software Engineering: Using UML, Patterns, and Java portfolio. ID. . . Portfolio Table portfolio. ID . . . 34

Mapping Many-To-Many Associations In this case we need a separate table for the association City * Serves * city. Name Airport airport. Code airport. Name Separate table for “Serves” association Primary Key City Table city. Name Houston Albany Munich Hamburg Bernd Bruegge & Allen H. Dutoit Airport Table airport. Code IAH HOU ALB MUC HAM airport. Name Intercontinental Hobby Albany County Munich Airport Hamburg Airport Object-Oriented Software Engineering: Using UML, Patterns, and Java Serves Table city. Name airport. Code IAH Houston HOU Houston ALB Albany MUC Munich HAM Hamburg 35

Mapping the Tournament/Player association as a separate table Tournament * * Player Tournament table id name 23 novice 24 expert Bernd Bruegge & Allen H. Dutoit . . . Player table Tournament. Player. Association table tournament player 23 56 23 79 Object-Oriented Software Engineering: Using UML, Patterns, and Java id name 56 alice 79 john 36 . . .

Realizing Inheritance ¨ ¨ Relational databases do not support inheritance Two possibilities to map UML inheritance relationships to a database schema With a separate table (vertical mapping) t The attributes of the superclass and the subclasses are mapped to different tables By duplicating columns (horizontal mapping) t There is no table for the superclass t 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 37

Realizing inheritance with a separate table User name Player credits League. Owner max. Num. Leagues User table id name 56 zoe 79 john . . . role League. Owner Player League. Owner table id 56 max. Num. Leagues 12 Bernd Bruegge & Allen H. Dutoit Player table. . . id credits 79 126 Object-Oriented Software Engineering: Using UML, Patterns, and Java . . . 38

Realizing inheritance by duplicating columns User name League. Owner max. Num. Leagues Player credits League. Owner table id name 56 zoe Bernd Bruegge & Allen H. Dutoit Player table max. Num. Leagues. . . id name credits 12 79 john 126 Object-Oriented Software Engineering: Using UML, Patterns, and Java . . . 39

Comparison: Separate Tables vs Duplicated Columns ¨ 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 J We can add attributes to the superclass easily by adding a column to the superclass table L Searching for the attributes of an object requires a join operation. ¨ Duplicated columns L Modifying the database schema is more complex and error-prone J 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 40

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 41

Documenting the Object Design: The Object Design Document (ODD) ¨ Object design document Same as RAD +. . . … + additions to object, functional and dynamic models (from solution domain) … + Navigational map for object model … + Javadoc documentation for all classes Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 42

Criteria for ODD ¨ Restrictiveness A specification should be precise enough that it excludes unwanted implementations. Preconditions and postconditions specifying border cases is one way to achieve restrictive specifications. ¨ Generality A specification, however, should not restrict its implementation. ¨ Clarity A specification should be easily and unambiguously understandable by developers. Certain behaviors are more easily described in natura 1 language, whereas boundary cases can be described with constraints and exceptions. Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 43

Approaches to documenting object design ¨ Self-contained ODD generated from model. We write and maintain a new UML model using a tool and generate the document automatically. This document would duplicate any application objects identified during analysis. Disadvantages: t redundancy with the Requirements Analysis Document (RAD) t high level of effort for maintaining consistency with the RAD. t This often leads to an RAD and an ODD that are inaccurate or out of date. ¨ ODD as extension of the RAD the object design is considered as the set of application objects augmented with solution objects (we add solution objects to the RAD) Advantage t maintaining consistency between the RAD and the ODD becomes much easier Disadvantages t Polluting the RAD with information that is irrelevant to the client and the user. ¨ ODD ernbedded into source code. We embed the ODD into the source code. t We first represent the ODD using a modeling tool. t Once the ODD becomes stable, we use the modeling tool to generate class stubs. We describe each class interface using tagged comments that distinguish source code comments from object design descriptions. t Once the object design model is documented in the code, we abandon the initial object design model. Advantage Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 44 t Consistency between the object design model and the source code

Analysis Embedded ODD approach Analysis model Document analysis RAD System design Subsystem decomposition Design goals Object design Initial object design model Generate class stubs Initial class stubs Implementation Commented code Bernd Bruegge & Allen H. Dutoit Document object design ODD Object-Oriented Software Engineering: Using UML, Patterns, and Java 45

Documenting Object Design: ODD Conventions ¨ Each subsystem in a system provides a service (see Chapter on System Design) Describes the set of operations provided by the subsystem ¨ Specifying a service operation as Signature: Name of operation, fully typed parameter list and return type Abstract: Describes the operation Pre: Precondition for calling the operation Post: Postcondition describing important state after the execution of the operation Use Java. Doc for the specification of service operations. Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 46

Java. Doc ¨ ¨ ¨ Add documentation comments to the source code. A doc comment consists of characters between /** and */ When Java. Doc parses a doc comment, leading * characters on each line are discarded. First, blanks and tabs preceding the initial * characters are also discarded. Doc comments may include HTML tags Example of a doc comment: /** * This is a <b> doc </b> comment */ Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 47

More on Java Doc ¨ ¨ Doc comments are only recognized when placed immediately before class, interface, constructor, method or field declarations. When you embed HTML tags within a doc comment, you should not use heading tags such as <h 1> and <h 2>, because Java. Doc creates an entire structured document and these structural tags interfere with the formatting of the generated document. Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 48

Class and Interface Doc Tags @author name-text Creates an “Author” entry. @version-text Creates a “Version” entry. @see classname Creates a hyperlink “See Also classname” @since-text Adds a “Since” entry. Usually used to specify that a feature or change exists since the release number of the software specified in the “since-text” @deprecated-text Adds a comment that this method can no longer be used. Convention is to describe method that serves as replacement Example: @deprecated Replaced by set. Bounds(int, int). Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 49

Constructor and Method Doc Tags ¨ Can contain @see tag, @since tag, @deprecated as well as: @parameter-name description Adds a parameter to the "Parameters" section. The description may be continued on the next line. @return description Adds a "Returns" section, which contains the description of the return value. @exception fully-qualified-class-name description Adds a "Throws" section, which contains the name of the exception that may be thrown by the method. The exception is linked to its class documentation. @see classname Adds a hyperlink "See Also" entry to the method. Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 50

Example: Specifying a Service in Java /** Office is a physical structure in a building. It is possible to create an * instance of a office; add an occupant; get the name and the number of * occupants */ public class Office { /** Adds an occupant to the office * @param NAME name is a nonempty string */ public void Add. Occupant(string name); /** @Returns the name of the office. Requires, that Office has been initialized with a name */ public string Get. Name(); . . } Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 51

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 52

Additional Slides Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 53

More Terminology ¨ Roundtrip Engineering Forward Engineering + reverse engineering Inventory analysis: Determine the Delta between Object Model and Code Together-J and Rationale provide tools for reverse engineering ¨ Reengineering Used in the context of project management: Provding new functionality (customer dreams up new stuff) in the context of new technology (technology enablers) Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 54

Statistics as a product in the Game Abstract Factory Game Tournament create. Statistics() Chess. Game Tic. Tac. Toe. Game Statistics update() get. Stat() TTTStatistics Bernd Bruegge & Allen H. Dutoit Chess. Statistics Object-Oriented Software Engineering: Using UML, Patterns, and Java Default. Statistics 55

N-ary association class Statistics relates League, Tournament, and Player Statistics 1 * 1 1 0. . 1 Game Bernd Bruegge & Allen H. Dutoit 0. . 1 League 0. . 1 Tournament Object-Oriented Software Engineering: Using UML, Patterns, and Java 0. . 1 Player 56

Realization of the Statistics Association Tournament. Control Statistics. View Statistics. Vault update(match) get. Stat. Names(game) get. Stat(name, game, player) get. Stat(name, league, player) get. Stat(name, tournament, player) Statistics update(match, player) get. Stat. Names() get. Stat(name) Game create. Statistics() Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 57

Statistics. Vault as a Facade Tournament. Control Statistics. View Statistics. Vault update(match) get. Stat. Names(game) get. Stat(name, game, player) get. Stat(name, league, player) Statistics update(match, player) get. Stat. Names() get. Stat(name) Game get. Stat(name, tournament, player) create. Statistics() Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 58

Public interface of the Statistics. Vault class public class Statistics. Vault { public void update(Match m) throws Invalid. Match, Match. Not. Completed {. . . } public List get. Stat. Names() {. . . } public double get. Stat(String name, Game g, Player p) throws Unknown. Statistic, Invalid. Scope {. . . } public double get. Stat(String name, League l, Player p) throws Unknown. Statistic, Invalid. Scope {. . . } public double get. Stat(String name, Tournament t, Player p) throws Unknown. Statistic, Invalid. Scope {. . . } } Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 59

Database schema for the Statistics Association Statistics table id: long scopetype: long player: long Statistic. Counters table id: long name: text[25] value: double Game table id: long . . . Bernd Bruegge & Allen H. Dutoit League table id: long . . . Object-Oriented Software Engineering: Using UML, Patterns, and Java Tournament table id: long . . . 60

Restructuring Activities ¨ ¨ ¨ Realizing associations Revisiting inheritance to increase reuse Revising inheritance to remove implementation dependencies Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 61

Realizing Associations ¨ Strategy for implementing associations: Be as uniform as possible Individual decision for each association ¨ Example of uniform implementation 1 -to-1 association: t Role names are treated like attributes in the classes and translate to references 1 -to-many association: t t "Ordered many" : Translate to Vector "Unordered many" : Translate to Set Qualified association: t Translate to Hash table Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 62

Unidirectional 1 -to-1 Association Object design model before transformation Zoom. In. Action Map. Area Object design model after transformation Zoom. In. Action Map. Area -zoom. In: Zoom. In. Action +get. Zoom. In. Action() +set. Zoom. In. Action(action) Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 63

Bidirectional 1 -to-1 Association Object design model before transformation Zoom. In. Action 1 Map. Area 1 Object design model after transformation Zoom. In. Action -target. Map: Map. Area +get. Target. Map() +set. Target. Map(map) Bernd Bruegge & Allen Dutoit Map. Area -zoom. In: Zoom. In. Action +get. Zoom. In. Action() +set. Zoom. In. Action(action) Object-Oriented Software Engineering: Conquering Complex and Changing Systems 64

1 -to-Many Association Object design model before transformation Layer 1 * Layer. Element Object design model after transformation Layer -layer. Elements: Set +elements() +add. Element(le) +remove. Element(le) Bernd Bruegge & Allen Dutoit Layer. Element -contained. In: Layer +get. Layer() +set. Layer(l) Object-Oriented Software Engineering: Conquering Complex and Changing Systems 65

Qualification Object design model before transformation Scenario simname * 0. . 1 Simulation. Run Object design model after transformation Scenario -runs: Hashtable +elements() +add. Run(simname, sr: Simulation. Run) +remove. Run(simname, sr: Simulation. Run) Bernd Bruegge & Allen Dutoit Simulation. Run -scenarios: Vector +elements() +add. Scenario(s: Scenario) +remove. Scenario(s: Scenario) Object-Oriented Software Engineering: Conquering Complex and Changing Systems 66

Increase Inheritance ¨ ¨ Rearrange and adjust classes and operations to prepare for inheritance Abstract common behavior out of groups of classes If a set of operations or attributes are repeated in 2 classes the classes might be special instances of a more general class. ¨ Be prepared to change a subsystem (collection of classes) into a superclass in an inheritance hierarchy. Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 67

Building a super class from several classes ¨ Prepare for inheritance. All operations must have the same signature but often the signatures do not match: Some operations have fewer arguments than others: Use overloading (Possible in Java) Similar attributes in the classes have different names: Rename attribute and change all the operations. Operations defined in one class but no in the other: Use virtual functions and class function overriding. ¨ ¨ Abstract out the common behavior (set of operations with same signature) and create a superclass out of it. Superclasses are desirable. They increase modularity, extensibility and reusability improve configuration management ¨ Turn the superclass into an abstract interface if possible Use Bridge pattern Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 68

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. Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 69

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 Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 70

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 Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 71

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. Abbott's textual analysis rules Every student receives a number at the first day in in the university. Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 72

Optimization Activities: Collapsing Objects Matrikelnumber Student ID: String Student Matrikelnumber: String Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 73

To Collapse or not to Collapse? ¨ Collapse a class into an attribute if the only operations defined on the attributes are Set() and Get(). Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 74

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: t t t 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) Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 75
![Optimization Activities: Delaying Complex Computations Image filename: String data: byte[] width() height() paint() Image Optimization Activities: Delaying Complex Computations Image filename: String data: byte[] width() height() paint() Image](http://slidetodoc.com/presentation_image_h2/6c10e774b2ebdf762c394db4a9e65ec6/image-76.jpg)
Optimization Activities: Delaying Complex Computations Image filename: String data: byte[] width() height() paint() Image filename: String width() height() paint() Image. Proxy filename: String width() height() paint() Bernd Bruegge & Allen Dutoit image 1 0. . 1 Real. Image data: byte[] width() height() paint() Object-Oriented Software Engineering: Conquering Complex and Changing Systems 76

Increase Inheritance Rearrange and adjust classes and operations to prepare for inheritance Generalization: Finding the base class first, then the sub classes. Specialization: Finding the sub classes first, then the base class Generalization is a common modeling activity. It allows to abstract common behavior out of a group of classes If a set of operations or attributes are repeated in 2 classes the classes might be special instances of a more general class. Always check if it is possible to change a subsystem (collection of classes) into a superclass in an inheritance hierarchy. Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 77

Generalization: Building a super class from several classes You need to prepare or modify your classes for generalization. All operations must have the same signature but often the signatures do not match: Some operations have fewer arguments than others: Use overloading (Possible in Java) Similar attributes in the classes have different names: Rename attribute and change all the operations. Operations defined in one class but no in the other: Use virtual functions and class function overriding. Superclasses are desirable. They increase modularity, extensibility and reusability improve configuration management Many design patterns use superclasses Try to retrofit an existing model to allow the use of a design pattern Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 78

Implement Associations Two strategies for implementing associations: 1. Be as uniform as possible 2. Make an individual decision for each association Example of a uniform implementation (often used by CASE tools) 1 -to-1 association: Role names are treated like attributes in the classes and translate to references 1 -to-many association: Always Translate into a Vector Qualified association: Always translate into to Hash table Bernd Bruegge & Allen Dutoit Object-Oriented Software Engineering: Conquering Complex and Changing Systems 79
- Slides: 79