You are on page 1of 60

SS ZG514 Object Oriented Analysis and Design

BITS Pilani
Pilani Campus

BITS Pilani
Pilani Campus

Lecture Session-13
21- 09-13
2

Mapping Designs to Code

BITS Pilani, Pilani Campus

Objectives
Map design artifacts to code in an object-oriented language Class definitions from DCDs Methods from interaction diagrams

Analysis artifact changes

BITS Pilani, Pilani Campus

Implementation Model
Interactions and DCDs complete for an iteration Sufficient detail exists for code generation Implementation model includes: Source code, database definitions, JSP/XML/HTML pages, etc.

BITS Pilani, Pilani Campus

Implementation Stimulates Change


Design results are incomplete During programming and testing: Details are uncovered Defects are discovered and resolved The design model must be updated to reflect these refinements

BITS Pilani, Pilani Campus

Programming and the Development Process

BITS Pilani, Pilani Campus

Mapping Designs to Code


Write source code for: Class and interface definitions Method definitions Work from OOA/D artifacts Create class definitions for Design Class Diagrams (DCDs) Create methods from Interaction diagrams

BITS Pilani, Pilani Campus

Design Class Diagrams


DCDs contain class or interface names, superclasses, method signatures, and simple attributes.

These are sufficient for basic class definitions.


Elaborate from associations to add reference attributes.

BITS Pilani, Pilani Campus

From DCD to Java class


public class SalesLineItem { private int quantity; private ProductDescription description; public SalesLineItem(ProductDescription desc, int qty) { ... } public Money getSubtotal() { ... } }

ProductDescription SalesLineItem quantity : Integer getSubtotal() : Money ... description description : Text price : Money 1 itemID : ItemID

BITS Pilani, Pilani Campus

Reference Attributes
Reference Attributes are suggested by associations and navigability in a class diagram. Note that reference attributes may be implied rather than explicit on a class diagram. You may have to ask How is this association accomplished.

BITS Pilani, Pilani Campus

Role Names
Each end of an association is a role. Reference Attributes are often suggested by role names.

SalesLineItem productSpec

Described-by productSpec

Product Specification Description

BITS Pilani, Pilani Campus

Interaction Diagrams
Interaction Diagrams and Operation Contracts are used to specify methods. They give most of the details for what the method does.

BITS Pilani, Pilani Campus

The Register Class


public class Register { private ProductCatalog catalog; private Sale currentSale; public Register(ProductCatalog pc) {...} public void endSale() {...} public void enterItem(ItemID id, int qty) {...} public void makeNewSale() {...} public void makePayment(Money cashTendered) {...} } catalog 1 ... getProductDesc(...) ProductCatalog

Sale Register ... endSale() enterItem(id: ItemID, qty : Integer) makeNewSale() makePayment(cashTendered : Money) currentSale 1 isComplete : Boolean time : DateTime

becomeComplete() makeLineItem(...) makePayment(...) [Larman getTotal() 2002]

BITS Pilani, Pilani Campus

enterItem Method Detail


{ ProductDescription desc = catalog.ProductDescription(id); currentSale.makeLineItem(desc, qty); }

enterItem(id, qty) :Register

2: makeLineItem(desc, qty) :Sale

1: desc := getProductDescription(id)

:Product Catalog

BITS Pilani, Pilani Campus

Containers
Where an object must maintain visibility to a group of other objects, such as a group of Sales Line Items in a Sale, object-oriented languages often use an intermediate container or collection. These will be suggested by a multiplicity value greater than one on a class diagram.

BITS Pilani, Pilani Campus

Collection classes
public class Sale { ... private List lineItems = new ArrayList(); } Sale isComplete : Boolean time : DateTime lineItems becomeComplete() makeLineItem() makePayment() getTtotal() 1..* SalesLineItem quantity : Integer getSubtotal()

A collection class is necessary to maintain attribute visibility to all the SalesLineItems.

BITS Pilani, Pilani Campus

Coupling drives code


Ideally, least-coupled classes will be created first and most coupled classes last. That way, you can describe the reference attributes as you go instead of going back to revise the class definitions later. Obviously, a class cannot have a major dependency on a class that will be implemented in a later iteration.

BITS Pilani, Pilani Campus

Implementation & Testing Order


Store address : Address name : Text addSale(...) 1 ... 1..* getProductDesc(...) ... 1 1 Register ... endSale() enterItem(...) makeNewSale() makePayment(...) 1

7
1 ProductCatalog

ProductDescription description : Text price : Money itemID : ItemID

Sale isComplete : Boolean time : DateTime becomeComplete() makeLineItem(...) makePayment(...) getTotal() ...

5
SalesLineItem 1..* quantity : Integer getSubtotal()

*
1 ...

Payment amount : Money

From least-coupled to most-coupled


BITS Pilani, Pilani Campus

Iteration-2

BITS Pilani, Pilani Campus

Monopoly Iteration-2
Expand basic players moving around board scenario to handle some special square rules: Each player starts with $1500 When player lands of Go, player receives $200 When player lands on Go-To-Jail, move to Jail When player lands on Income-Tax, player pays minimum of $200 or 10% of worth

BITS Pilani, Pilani Campus

New class diagram for Monopoly

BITS Pilani, Pilani Campus

NextGen POS Iteration-2


Iteration-2 will handle additional requirements: Support for third-party external services (i.e., different tax collectors) Complex pricing rules GUI window refreshes when sale total changes Constraint: only consider these requirements in context of Process Sale use case

BITS Pilani, Pilani Campus

SSD for external systems


Process Sale Pay by Credit Scenario :NextGenPOS System : Cashier actor :TaxCalculator actor :CreditAuthorization Service actor :Accounts

makeNewSale

enterItem(itemID, quantity)

description, total

endSale taxLineItems = getTaxes( sale ) total with taxes makeCreditPayment (credNum, expiryDate) reply = requestApproval(request) postReceivable( receivable ) postSale( sale )

BITS Pilani, Pilani Campus

Fig. 24.1

Generalisation- POS

BITS Pilani, Pilani Campus

Generalisation-Specialisation

BITS Pilani, Pilani Campus

Subclass-Associations Of Interest

BITS Pilani, Pilani Campus

Refactoring
Refactoring: changing a software system by improving its internal structure without changing its external behavior I.e., restructure code in a disciplined way Make code easier to understand and cheaper to modify Counteracts entropy of software by promoting more order Identify heavily used or time consuming code Refactoring leads to design patterns: why? Smalltalk community used refactoring to develop the Model-View-Controller and other frameworks

BITS Pilani, Pilani Campus

When to Refractor?
When you do a Code Review or Walkthrough

I.e., in subsequent iterations (polymorphism in Monopoly)

When you add a function Helps you to understand the code you are modifying Sometimes existing design does not allow you to easily add the feature When you need to fix a bug A bug report is a sign code needs refactoring: Why? Code was not clear enough to see the bug in the first place

BITS Pilani, Pilani Campus

Refactoring Goals
Remove duplicate code Improve clarity Shorten methods Remove hard-coded constants Move methods to another class

BITS Pilani, Pilani Campus

Summary
Mapping design to code Class definitions from DCDs Methods from interaction diagrams Analysis artifact changes Refactoring

BITS Pilani, Pilani Campus

Gang of Four Design Patterns

BITS Pilani, Pilani Campus

Gang of Four
Pattern-based design was introduced into architecture and engineering in the 1950's Almost immediately, software engineers began using patterns for designing software It wasn't until a group of four researchers combined forces that pattern-based design became well-known and commonplace

This group was known as the gang of four (GoF)

BITS Pilani, Pilani Campus

Gang of Four
The gang of four (GoF) is:
Erich Gamma Richard Helm Ralph Johnson John Vlissides

They are the authors of the famous text "Design Patterns: Elements of Reusable Object-Oriented Software"

BITS Pilani, Pilani Campus

Design Pattern: Introduction


There are recurring/characteristic problems during a design activity. E.g., A certain class should have only one instance. Known as Pattern. Designers come up with various solutions to deal with these problems.

Eventually, best known solutions are collected and documented as Design Patterns.

BITS Pilani, Pilani Campus

Design Pattern: Definition


A Design Pattern is the outline of a reusable solution to a general problem encountered in a particular context: describes a recurring problem describes the core of the solution to that problem.

Design Patterns are named to facilitate people using and discussing them.

BITS Pilani, Pilani Campus

Design Pattern: Advantages


1. Reuse existing, high-quality solutions to recurring design problems. 2. Improve future design: Solutions to new problems can be obtained with higher quality. 3. Shift the level of thinking to a higher perspective. 4. Use common terminology to improve communications within team members. 5. Improve documentation: smaller, simpler. 6. Use a right design, not just one that works. 7. Studying patterns is an effective way to learn from the experience of others.
BITS Pilani, Pilani Campus

Three Types of GoF Patterns


Creational patterns:
Deal with initializing and configuring objects

Structural patterns:
Composition of classes or objects Decouple interface and implementation of classes

Behavioral patterns:
Deal with dynamic interactions among societies of objects How they distribute responsibility

BITS Pilani, Pilani Campus

The Classification of Design Patterns

BITS Pilani, Pilani Campus

Structural patterns
Assemble objects to realize new functionality Exploit flexibility of object composition at run-time Not possible with static class composition Structure patterns are concerned with how classes and objects are composed to form large structures. Different categories Adapter Bridge Composite Decorator Faade Flyweight Proxy

BITS Pilani, Pilani Campus

Adapter Pattern
Adapters are used to enable objects with different interfaces to communicate with each other. Adapter Pattern tells us how to wrap up existing classes inside a new target interface, when the need arises to reuse existing class implementations but with a different interface for the clients.

They are also termed as wrappers.

BITS Pilani, Pilani Campus

Adapter Pattern Real World Example

BITS Pilani, Pilani Campus

Adapter Pattern Real World Example

BITS Pilani, Pilani Campus

Adapter Pattern Real World Example


Example (non-software) U.S. electrical system: 110 VAC @ 60 Hz. European electrical system: 220 VAC @ 50 Hz. How can we use U.S. appliances in Europe? Adapters!

BITS Pilani, Pilani Campus

Adapter Pattern Example

Solution

BITS Pilani, Pilani Campus

Adapter Description
Intent

Convert the interface of a class to an interface expected by the users of the class. Allows classes to work together even though they expect incompatible interfaces.

BITS Pilani, Pilani Campus

Adapter - Intent
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. Wrap an existing class with a new interface. Also Known As -> Wrapper
BITS Pilani, Pilani Campus

Motivation
Sometimes a toolkit or class library can not be used because its interface is incompatible with the interface required by an application. We can not change the library interface, since we may not have its source code. Even if we did have the source code, we probably should not change the library for each domainspecific application.

BITS Pilani, Pilani Campus

Variations in Adapters
Class Adapters Use multiple inheritance to compose classes Object Adapters Object adapters use a compositional technique to adapt one interface to another.
BITS Pilani, Pilani Campus

Motivation
Sometimes a toolkit or class library can not be used because its interface is incompatible with the interface required by an application We can not change the library interface, since we may not have its source code Even if we did have the source code, we probably should not change the library for each domain-specific application

BITS Pilani, Pilani Campus

Motivation

BITS Pilani, Pilani Campus

Participants
Target (Shape) defines the domain-specific interface that Client uses. Client (DrawingEditor) collaborates with objects conforming to the Target interface. Adaptee (TextView) defines an existing interface that needs adapting. Adapter (TextShape) adapts the interface of Adaptee to the Target interface.

BITS Pilani, Pilani Campus

Structure
A class adapter uses multiple inheritance to adapt one interface to another: adapts Adaptee to Target by committing to a concrete Adapter class. As a consequence, a class adapter won't work when we want to adapt a class and all its subclasses.

BITS Pilani, Pilani Campus

Structure
An object adapter relies on object composition: lets a single Adapter work with many Adapteesthat is, the Adaptee itself and all of its subclasses (if any). The Adapter can also add functionality to all Adaptees at once.

BITS Pilani, Pilani Campus

Collaborations

Clients call operations on the Adapter instance and Adapter delegates request to Adaptee.
BITS Pilani, Pilani Campus

Adaptability
Use the adapter when
Want to use an existing class and its interface doesnt match the one we need. (Object Adapters only) we need to use several existing subclasses, but its impractical to adapt their interface by sub classing every one. An object adapter can adapt the interface of its parent class.

BITS Pilani, Pilani Campus

Consequences
Class Adapter
Adapts Adaptee to Target by committing to a concrete Adapter class. Lets Adapter override some of the Adaptees behavior by subclassing. Introduces only one object and no additional pointer indirection is needed to get the adaptee.

Object Adapter
Lets a single adapter work with a group of adaptees such as a base class and all its sub classes. The adapter can add functioanlity to all adaptees at once. Makes it harder to override Adaptee behavior as the Adapter may not know with what Adaptee it is working with.
BITS Pilani, Pilani Campus

POS example: Instantiate adapters for external services


interface ITaxCalculatorAdapter getTaxes( Sale ) : List of TaxLineItems Adapters use interfaces and polymorphism to add a level of indirection to varying APIs in other components.

TaxMasterAdapter

GoodAsGoldTaxPro Adapter

getTaxes( Sale ) : List of TaxLineItems getTaxes( Sale ) : List of TaxLineItems

interface IAccountingAdapter postReceivable( CreditPayment ) postSale( Sale ) ...

interface ICreditAuthorizationService Adapter requestApproval(CreditPayment,TerminalID, MerchantID) ...

interface IInventoryAdapter SAPAccountingAdapter GreatNorthernAccountingAdapter ...

postReceivable( CreditPayment ) postSale( Sale ) ...

postReceivable( CreditPayment ) postSale( Sale ) ...

BITS Pilani, Pilani Campus

Fig. 26.1

Using an Adapter: adapt postSale request to SOAP XML interface


:Register makePayment ... SOAP over HTTP postSale( sale ) xxx actor : SAPSystem : SAPAccountingAdapter

the Adapter adapts to interfaces in other components

BITS Pilani, Pilani Campus

Benefits of Adapter pattern


Reduces coupling to implementation specific details Polymorphism and Indirection reveals essential behavior provided Including name of design pattern in new class (e.g., TaxMasterAdapter) in class diagrams and code communicates to other developers in terms of known design patterns

BITS Pilani, Pilani Campus

You might also like