CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

59
CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit

Transcript of CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

Page 1: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431:From Models to Implementation

Some material from Bruegge, Dutoit

Page 2: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Outline

• From Object Model to Code• Mapping models to code

• Operations on the object model:• Optimizations to address performance requirements

• Implementation of class model components• Realization of associations• Realization of operation contracts

• From Object Model to Persistent Data

• Summary

Page 3: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Development Activities

• Improve modularity and performance

• Transform associations into references, because programming languages do not support associations

• Relations to functions

• If the programming language does not support contracts, write code for detecting and handling contract violations (or leave as documentation)

Page 4: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Model-Driven Engineering (MDE)

• Vision• Object model realizes the use case, which directly

maps to implementation (model-driven engineering)• Maybe implementation even generated

• Reality• Model and code out of sync• Examples:

• A new parameter added to an operation, only added to the source code, but not to the object model

• Additional attributes are added to an entity object, but the data base table is not updated (as a result, the new attributes are not persistent)

Page 5: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Object Model Code; Issues

• No direct language construct for UML associations

• Transformed into collections of object references

• Most languages do not support contracts (invariants, pre and post conditions)

• Contracts manually transformed to error detection and handling code, asserts, etc. (or ignored)

• If a model changes, effecting the same change in code is a manual process

Page 6: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Transformations

Page 7: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Model Transformation

• Takes as input a model conforming to a meta model (for example the MOF metamodel) and produces as output another model conforming to the metamodel

• Model transformations are used in MDA (Model Driven Architecture)

Page 8: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Model Transformation Example

• Object design model before transformation:

• Object design model after transformation:

Page 9: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Same Transformation in Code: Refactoring: Pull Up Field

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 LeagueOwner extends User {

//...

}

public class Advertiser extends User {

//...

}

Page 10: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Refactoring Example: Pull Up Constructor Body

public class User {

private String email;

}

public class Player extends User {

public Player(String email) {

this.email = email;

}

}

public class LeagueOwner extends User{

public LeagueOwner(String email) {

this.email = email;

}

}

public class Advertiser extends User{

public Advertiser(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 LeagueOwner extends User {

public LeagueOwner(String email) {

super(email);

}

}

public class Advertiser extends User {

public Advertiser(String email) {

super(email);

}

}

Page 11: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Refactoring

• Refactorings cataloged the same was ay design patterns

• http://refactoring.com/catalog/index.html

• Many language IDEs offer powerful refactoring tools

Page 12: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Forward Engineering Example

Page 13: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

More Forward Engineering Examples

• 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

Page 14: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Reverse Engineering Example

• Javadoc, Doxygen, …• Extract documentation from source code comments• Doxygen is open source, based on Oracle Javadoc

• Roundtrip engineering• Move between a UML view and code at will

Page 15: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

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

Page 16: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

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:• Add redundant associations to minimize access cost

• What are the most frequent operations? ( Sensor data lookup?)• How often is the operation called? (30 times/mo, every 50 ms)

• As an object designer you must strike a balance between efficiency and clarity

• Optimizations will make your models more obscure

Page 17: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Object Design Optimizations (cont.)

• Store derived attributes• Example: Define new classes to store information locally (database

cache, proxy pattern)

• Problem with derived attributes:• Derived attributes must be updated when base values change

• 3 ways to deal with the update problem:• Explicit code: Implementer 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 the active value is changed (observer pattern, data trigger)

Page 18: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Model Transformations for Efficiency - Examples

• Optimizing access paths• Possibly include redundant access paths

• From “many” to “one” association through qualifications

• Re-position attributes• Fold “uninteresting” attributes to calling class

• Collapse objects (turn into attributes)

• Delay expensive computations

• Cache computation results

Page 19: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Collapsing Objects

• Object design model before transformation:

• Object design model after transformation:

• Turning an object into an attribute of another object is usually done if the object does not have any interesting dynamic behavior (only get/set operations)

Page 20: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Delaying Expensive Operations• Object design model before transformation:

• Object design model after transformation:

Proxy Pattern

Page 21: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Forward Engineering: Mapping UML Model to Source Code

• Goal: Translate UML-Model with inheritance - want to translate it into source code

• Solution space: E.g. Java provides following mechanisms:

• Overwriting of methods (default in Java)• Final classes• Final methods• Abstract methods• Abstract classes• Interfaces

Page 22: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

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

Page 23: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Unidirectional 1:1 Association

Page 24: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Bidirectional 1:1 Association

Page 25: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Bidirectional 1:N Association

Page 26: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Bidirectional N:N Association

Page 27: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Bidirectional Qualified Association

Page 28: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Bidirectional Qualified Association (2)

Page 29: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Summary: Implementing Associations

• Strategy for implementing associations:• Be as uniform as possible• Individual decision for each association

• Example of uniform implementation• 1:1 association:

• Role names are treated like attributes in the classes and translate to references

• 1:N association:• “Ordered many” : Translate to Vector• “Unordered many” : Translate to Set

• Qualified association:• Translate to Hash table

Page 30: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Model-Driven Engineering (MDE)• http://en.wikipedia.org/wiki/Model_Driven_Engineering

• MDE refers to a range of development approaches based on the use of SW modeling as a primary form of expression. Sometimes models are constructed to a certain level of detail, and then code is written by hand in a separate step.

• Sometimes complete models are built including executable actions. Code can be generated from the models, ranging from system skeletons to complete, deployable products.

• With the introduction of UML, MDE has become very popular today with a wide body of practitioners and supporting tools. More advanced types of MDE have expanded to permit industry standards which allow for consistent application and results. The continued evolution of MDE has added an increased focus on architecture and automation.

• MDE technologies with a greater focus on architecture and corresponding automation yield higher levels of abstraction in SW development. This abstraction promotes simpler models with a greater focus on problem space. Combined with executable semantics this elevates the total level of automation possible.

• OMG has developed a set of standards called model-driven architecture (MDA), building a foundation for this advanced architecture-focused approach.

Page 31: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

MDE Historical View• First tools to support MDE were Computer-Aided Software

Engineering (CASE) tools developed in 1980s• Companies like Integrated Development Environments (IDE -

StP), Higher Order Software (now Hamilton Technologies, Inc., HTI), Cadre Technologies, Bachman Information Systems, and Logicworks (BP-Win and ER-Win) were pioneers

• The government got involved in the modeling definitions creating the IDEF specifications.

• New modeling languages (Booch, Rumbaugh, Jacobson, Ganes, Sarson, Harel, Shlaer, Mellor, others) led to Unified Modeling Language (UML)

• Rational Rose was first dominant UML product, from Rational, now IBM

• CASE had same problem that current MDA/MDE tools have today: model gets out of sync with source code

Page 32: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Terminology Review

• Roundtrip Engineering• Forward Engineering + reverse engineering• Inventory Analysis: determine between object

model and code• Together-J, Rationale,… provide tools for reverse

engineering

• Reengineering• Used in context of project management:• Providing new functionality (additional customer

needs) in context of new technology (technology enablers)

Page 33: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Implementing Contract Violations

• Many OO languages do not have built-in support for contracts

• Can use their exception mechanisms for signaling and handling contract violations

• In Java we use the try-throw-catch mechanism

• Example:• Assume acceptPlayer() operation of TournamentControl is invoked with a player who is already part of the Tournament

• In this case acceptPlayer() in TournamentControl should throw an exception of type KnownPlayer

Page 34: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Implementing a Contract• Check each pre-condition:

• Check the pre-condition at beginning of method• Raise an exception if the pre-condition is false

• Check each post-condition:• Check post-condition at end of method

• Raise an exception if the post-condition is false. If more than one post-condition is false, raise an exception only for the first violation

• Check each invariant:• Check invariants when checking pre- and post-

conditions

• Deal with inheritance:• Add the checking code for pre- and post-conditions into

methods that can be called from the class

Page 35: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Mapping Contracts to Exceptions

• Checking code slows down your program• If too slow, omit the checking code for private and

protected methods• If still too slow, focus on components with the

longest life• Omit checking code for post-conditions and invariants for

all other components

Page 36: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Outline

• From Object Model to Code• Mapping models to code

• Operations on the object model:• Optimizations to address performance requirements

• Implementation of class model components• Realization of associations• Realization of operation contracts

• From Object Model to Persistent Data

• Summary

Page 37: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

From Models to Persistent Data

• Random complaint from somewhere:• “UML Overemphasizes programming jargon, ignores

databases”

• However, UML models can also be used for generating a schema for a relational database

• Schema derivable from class diagrams

• Relational database only has a single entity type: table

• Some of UML class diagrams’ richer structure lost

• Tools offer automation (to both directions)

Page 38: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

From Class Diagrams to Tables• Basics of the mapping

• class mapped to a table• class attribute mapped to a column of a table• instance of a class is a row of a table• 1:1 association mapped to a foreign key

• or two classes coalesced to one table

• 1:N association mapped to a foreign key• N:N association mapped to a table of its own

• No counterpart for methods

• Object identity implicitly serves as a unique “key” in UML class diagrams

• It may be necessary to add an explicit identity attribute to a table corresponding to a class

Page 39: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Example: Class to Table

• This table might be OK w/o an ID attribute• Name seldom changes• OTOH, refs from other tables need to use the (relatively long) NAME

• Decisions on representing data must be made• Constraints in the model, and eventually code, need to be updated to

reflect the decisions

Page 40: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Why Unique ID is a Good Idea

• Springfield Township, Bradford County, PA• Springfield Township, Bucks County, PA• Springfield Township, Delaware County, PA• Springfield Township, Erie County, PA• Springfield Township, Fayette County, PA• Springfield Township, Huntingdon County, PA• Springfield Township, Mercer County, PA• Springfield Township, Montgomery County, PA• Springfield Township, York County, PA

Page 41: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Data Representation• 2 char for state is okay in US

• What about county name (see previous slide)?

• Is 30 char okay for city name?• Rolling Hills Estates, CA – 21 char• Rancho Palos Verdes, CA – 19 char• Truth or Consequences NM – 19 char• Washington-on-the-Brazos, TX – 24 char• Winchester-on-the-Severn, MD – 24 char• Slovenska Narodna Podporna Jednota, PA – 34 char• Kinney and Gourlays Improved City Plat, UT – 38 char• “El Pueblo de Nuestra Señora la Reina de los Ángeles de la

Porciúncula” LA – 68 char + accents• Might be 1781 name of LA

• 40 characters is safer, but lot of wasted space

• Int for population?• 32-bit int is plenty for humans and pets

Page 42: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

1:N Association

• Is it really a 1:N association?

• Implemented as foreign key

Page 43: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Reminder: Keys

Candidate Key A set of attributes that uniquely identifies a row of a table

Primary Key One of the candidate keys selected to be used as the key of the table

Foreign Key Set of attributes that references the primary key of another table

Page 44: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Example: Keys

Al Jumahiriyah al Arabiyah al Libiyah ash Shabiyah al Ishtirakiyah al Uzma

Problem!

Page 45: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Example: 1:N

Probably okay

32-bit INT marginal

Page 46: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

1:1 Associations

Page 47: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Foreign Key Can be Placed in Either Table

Page 48: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Navigation

• Previous tables corresponded to diagram on left

• (Fast) navigability in both directions may require indices

Page 49: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

1:1: Possible to Represent as One Table

Page 50: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

N:N Associations

Too short w/ “International

Airport” in name

Page 51: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Inheritance• No construct that would correspond to

inheritance in relational databases

• Two common approaches for mapping an inheritance association to a database schema

• Vertical Mapping• Different tables for superclass and subclass

attributes• If n subclasses, n + 1 tables

• Horizontal Mapping• Subclass tables contain base attributes• No table for the base class

Page 52: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Example Inheritance Hierarchy

Page 53: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Vertical Mapping

Page 54: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Horizontal Mapping

Page 55: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Comparison• Trade-off between modifiability and response time

• Are changes likely in the superclass?• Performance requirements for queries?

• Vertical mapping• Adding attributes to superclass easy• Accessing all attributes of employee or manager

requires a join

• Horizontal mapping• Changes to superclass result in more complex

schema modifications• Objects not fragmented across several tables faster

queries

Page 56: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

OODBMS, NoSQL, …

• Alternatives to Relational Database

• May offer a more direct mapping between a model and persistent data

• Joins not needed (nor offered)• Access through pointers• Navigability fixed

• OODBMS:• Programming language and database schema use

the same type definitions

Page 57: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Thoughts About Model-Code-DB Mappings

• Consistency important• Codify the process, always do in the same way• Use tools – object/relational mapping tools• http://

en.wikipedia.org/wiki/List_of_object-relational_mapping_software

• Beneficial to Avoid replicating information• Edited in one space, generated to other spaces• If lots of replication, information will get out of sync

Page 58: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Outline

• From Object Model to Code• Mapping models to code

• Operations on the object model:• Optimizations to address performance requirements

• Implementation of class model components• Realization of associations• Realization of operation contracts

• From Object Model to Persistent Data

• Summary

Page 59: CSCE 431: From Models to Implementation Some material from Bruegge, Dutoit.

CSCE 431 From Models to Implementation

Summary• Four mapping concepts

1. Model transformations• Improve the compliance of the object design model with a design goal

2. Forward engineering• Consistent transformation of models to code

3. Refactoring• “Preserve semantics, improve readability/modifiability”

4. Reverse engineering• “Extract design from code”

• Model transformations and forward engineering techniques• “Optimizing” within the class model• Mapping associations to collections• Mapping contracts to exceptions• Mapping class model to storage schemas