Download presentation
Presentation is loading. Please wait.
1
Object Design I: Reuse
2
Where are we? What comes next?
We have covered: Introduction to Software Engineering (Chapter 1) Modeling with UML (Chapter 2) Project Organization and Communication (Chapter 3) Requirements Elicitation (Chapter 4) Analysis (Chapter 5) System Design (Chapter 6 and 7) Today and next week Object Design (Chapter 8).
3
Outline of Today Definition and Terminology: Object Design vs Detailed Design System Design vs Object Design Object Design Activities Reuse examples Whitebox and Blackbox Reuse Object design leads also to new classes Implementation vs Specification Inheritance Inheritance vs Delegation Class Libraries and Frameworks
4
Object Design Purpose of object design:
Prepare for the implementation of the system model based on design decisions Transform the system model (optimize it) Investigate alternative ways to implement the system model Use design goals: minimize execution time, memory and other measures of cost. Object design serves as the basis of implementation. O bject design is the process of adding details to the requirements analysis and making implementation decisions The object designer must choose among different ways to implement the analysis model with the goal to minimize execution time, memory and other measures of cost. Requirements Analysis: Use cases, functional and dynamic model deliver operations for object model Object Design: Iterates on the models, in particular the object model and refine the models Object Design serves as the basis of implementation
5
Terminology: Naming of Design Activities
Methodology: Object-oriented software engineering (OOSE) System Design Decomposition into subsystems, etc Object Design Data structures and algorithms chosen Implementation Implementation language is chosen Methodology: Structured analysis/structured design (SA/SD) Preliminary Design Decomposition into subsystems, etc Data structures are chosen Detailed Design Algorithms are chosen Data structures are refined Implementation language is chosen. Object-Oriented methodologies use these terms: The System Design activity involves the decomposition of the system into subystems
6
System Development as a Set of Activities
System Model Existing Machine Problem Application objects Analysis Solution objects Design Off-the-shelf components are also sometimes called COTS (commercial off-the-shelf components) Custom objects Object Design Off-the-Shelf Components System Design
7
Design means “Closing the Gap”
“Subsystem 1”: Rock material from the Southern Sierra Nevada mountains (moving north) Example of a Gap: San Andreas Fault Customization closes the Object Design Gap between Application Objects and System Design Objects What is a gap? An example of a gap is the San Andreas fault shown here in this image This Information was found on the web: This image shows San Andreas Lake and Crystal Springs reservoir from the air, looking SouthEast from HERE. The highway paralleling the lakes to the left is Interstate 280, ``the most beautiful urban highway in the United States''. (And it is indeed very scenic.)This valley is remarkably straight because the San Andreas fault runs down its center. The San Andreas is a classic ``Strike Slip'' fault: the two sides (for the most part) move past each other horizontally. (San Francisco Bay is there at least partly because the block between the San Andreas on the West and the Hayward fault on the East has been downdropped a bit, but that motion is small compared to the tremendous horizontal displacements that have occurred along these faults.) The vegetation and terrain on either side of the lakes look different partly because the underlying rock IS geologically very different. The rock on the right came from the Southern Sierra Nevada mountains, and has been transported from several hundred miles to the South by motion along the fault. With each San Andreas earthquake, it continues a few more feet (or tens of feet) on its long slow journey North (eventually to be plastered onto Alaska?).San Andreas Lake (from which the fault takes its name) is a ``sag pond'' that naturally formed in the valley of the San Andreas fault. Strike slip faults are good places for lakes; the fault both creates a low spot to collect the water, and grinds up the rock underneath making an impermeable layer to hold the water in. Man has enlarged San Andreas lake with a dam, and created two additional lakes in the same valley, Upper and Lower Crystal Springs Reservoirs. The dam holding the reservoirs in place is under a bridge on highway 280 (but you might be distracted as you drive over it by the sight of the gleaming white ``dome home'', a spray-foam wonder visible from the same bridge on the other side). “Subsystem 3” closes the Gap: San Andreas Lake “Subsystem 2”: San Francisco Bay Area
8
Design means “Closing the Gap” between Problem and Existing Machine
Solution objects System Model Problem Machine Develop- ment Gap Requirements gap Application objects Custom objects Customization closes the Object Design Gap between Applplication Objects and System Design Objects What is a gap? An example of a gap is the andreas fault shown here in this image. This image shows San Andreas Lake and Crystal Springs reservoir from the air, looking SouthEast from HERE. The highway paralleling the lakes to the left is Interstate 280, ``the most beautiful urban highway in the United States''. (And it is indeed very scenic.)This valley is remarkably straight because the San Andreas fault runs down its center. The San Andreas is a classic ``Strike Slip'' fault: the two sides (for the most part) move past each other horizontally. (San Francisco Bay is there at least partly because the block between the San Andreas on the West and the Hayward fault on the East has been downdropped a bit, but that motion is small compared to the tremendous horizontal displacements that have occurred along these faults.) The vegetation and terrain on either side of the lakes look different partly because the underlying rock IS geologically very different. The rock on the right came from the Southern Sierra Nevada mountains, and has been transported from several hundred miles to the South by motion along the fault. With each San Andreas earthquake, it continues a few more feet (or tens of feet) on its long slow journey North (eventually to be plastered onto Alaska?).San Andreas Lake (from which the fault takes its name) is a ``sag pond'' that naturally formed in the valley of the San Andreas fault. Strike slip faults are good places for lakes; the fault both creates a low spot to collect the water, and grinds up the rock underneath making an impermeable layer to hold the water in. Man has enlarged San Andreas lake with a dam, and created two additional lakes in the same valley, Upper and Lower Crystal Springs Reservoirs. The dam holding the reservoirs in place is under a bridge on highway 280 (but you might be distracted as you drive over it by the sight of the gleaming white ``dome home'', a spray-foam wonder visible from the same bridge on the other side). Object design gap “Higher level Virtual Machine” System design gap
9
Object Design Activities consists of 4 Activities
1. Reuse: Identification of existing solutions Use of inheritance Off-the-shelf components and additional solution objects Use of Design patterns 2. Interface specification Describes precisely each class interface 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. Focus on Reuse and Specification Towards Mapping Models to Code
10
Object Design Activities
Specifying constraints Specifying types & signatures Identifying patterns Adjusting patterns Identifying missing attributes & operations Specifying visibility Specification Specifying exceptions Reuse Identifying components Adjusting components Select Subsystem We start here A Detailed View of Object Design Activities
11
Detailed View of Object Design Activities (ctd)
Collapsing classes Restructuring Optimization Revisiting inheritance Optimizing access paths Caching complex computations Delaying complex Check Use Cases Realizing associations
12
One Way to do Object Design
Identify the missing components in the design gap Make a build or buy decision to obtain the missing component => Component-Based Software Engineering: The design gap is filled with available components (“0 % coding”) Special Case: COTS-Development COTS: Commercial-off-the-Shelf The design gap is filled with commercial-off-the-shelf-components. => Design with standard components.
13
Design with Standard Components is similar to solving a Jigsaw Puzzle
Standard Puzzles: „Corner pieces have two straight edges“ Design with Standard Components is similar to solving a Jigsaw Puzzle What do we do if that is not true?. “Find” the puzzle piece There is no build and buy analogy in the solving a jigsaw puzzle, because all the pieces are in the box. So usually it is „Find“ the puzzle piece, unless you have lost one. In this case, you have to buy one or build one yourself Activities: Start with the architecture (subsystem decomposition) Identify the missing component Make a build or buy decision for the component Add the component to the system (finalize the design)
14
What do we do if we have non-Standard Components?
Advanced Jigsaw Puzzles
15
Apollo 13: “Houston, we’ve had a Problem!”
Lunar Module (LM): Living quarters for 2 astronauts on the moon Command Module (CM): Living quarters for 3 astronauts during the trip to and from the moon Service Module (SM): Batteries, etc Failure! Source: “With only 15 minutes of power left in the CM, CapCom told us to make our way into the LM. Fred and I quickly floated through the tunnel, leaving Jack to perform the last chores in our forlorn and pitiful CM ...” Outlook: • Time until reentry: about 2 1/2 days • 90 hours = Lots of battery power in Service Module to reentry (about 2 1/2 days). • Plenty of drinking water could be brought over from the command module. • Oxygen stores showed a margin of 95 hours. • With power kept up to only support the life-support, telemetry and communications equipment, cooling water would last 23 hours beyond reentry, battery 60 hours, ample to recharge the Command Modules batteries before separation. • One problem were the cartridges of lithium hydroxide that remove carbon dioxide from the spacecraft atmosphere. Carbon dioxide would poison the astronauts unless scrubbed from the lunar module atmosphere by lithium hydride canisters. But the lunar module had only enough lithium hydride for 4 man-days - plenty for the lunar landing but not the 12 man-day's worth needed now • There were plenty of CM’s cartridges but the CM’s cartridges (Square openings) did not fit the LM system (round openings) Available lithium hydride in LM: 60 hours for 2 Astronauts Needed: 88 hours for 3 Astronauts Available lithium hydride (for removing carbon dioxide) in CM: “Plenty” But: only 15 min power left The LM was designed for 2 astronauts staying 2 days on the moon (4 man-days) Redesign challenge: Can the LM be used for 12 man-days (2 1/2 days until reentry into Earth)? Proposal: Use the lithium hydride cartridges from the CM to extend life in LM Problem: Lithium hydride openings in CM were incompatible with scrubber in LM!
16
Incompatibility between LM Scrubber and CM Cartridge System
Design Gap Astronaut Question: How would you model the Astronaut? Answer: also as a subystem consisting of the human being, the suit with all its electronics and connection to the LM environmental system. CM Environmental Subsystem LM Environmental Subsystem LM Scrubber ObtainOxygen() Opening: Round CM_Cartridge ScrubCarbonMonoxide() Opening: Square
17
Apollo 13: “Fitting a square peg in a round hole”
Source: A SQUARE PEG IN A ROUND HOLE Carbon dioxide would poison the astronauts unless scrubbed from the lunar module atmosphere by lithium hydride canisters. But the lunar module had only enough lithium hydride for 4 man-days - plenty for the lunar landing but not the 12 man-day's worth needed now. With only 15 minutes of power left in the CM, CapCom told us to make our way into the LM. Fred and I quickly floated through the tunnel, leaving Jack to perform the last chores in our forlorn and pitiful CM that had seemed such a happy home less than two hours earlier. Fred said something that strikes me as funny as I read it now: "Didn't think I'd be back so soon." But nothing seemed funny in real time on that 13th of April, 1970. The trouble was the square lithium hydroxide canisters from the CM would not fit the round openings of those in the LM environmental system. After a day and a half in the LM a warning light showed us that the carbon dioxide had built up to a dangerous level, but the ground was ready. They had thought up a way to attach a CM canister to the LM system by using plastic bags, cardboard, and tape- all materials we had on board. Jack and I put it together: just like building a model airplane. The contraption wasn't very handsome, but it worked. It was a great improvisation- and a fine example of cooperation between ground and space. We would have died of the exhaust from our own lungs if Mission Control hadn't come up with a marvelous fix. "Backroom" experts at Mission Control worked many hours to devise the fix that possibly kept the astronauts from dying of carbon dioxide. CapCom Joe Kerwin led Astronaut Swigert, step by step, for an hour to build a contraption like the one the experts had constructed on Earth. It involved stripping the hose from a lunar suit and rigging the hose to the taped-over CM double canister, using the suit's fan to draw carbon dioxide from the cabin through the canister and expel it back into the LM as pure oxygen. Emergency scrubbers were built by Swigert and Haise. Photo above shows Swigert sitting next to a taped-over double canister and holding one end of a suit nozzle while Fred Haise used both his hands to manipulate the long hose. Underneath the canister is a "mailbox" built of arched cardboard, which was covered by a plastic bag. When Lovell later saw the rig put together on Earth, he said, "It looks just like the one we made." It saved the astronauts from possible death from carbon dioxide. Source:
18
A Typical Object Design Challenge: Connecting Incompatible Components
Command Module Lithium hydride canister in Command Module subsystem (which used square openings) Interface to the Lunar Module Environmental Subsystem (which used round openings) Source:
19
Adapter Pattern . Adapter Pattern: Connects incompatible components
It converts the interface of one component into another interface expected by the other (calling) component Used to provide a new interface to existing legacy components (Interface engineering, reengineering) Also known as a wrapper. The adapter pattern lets classes work together that couldn’t otherwise because of incompatible interfaces Object adapters are much more frequent. We will only cover object adapters (and call them therefore simply adapters)
20
Adapter Pattern New System Old System (“Legacy System”) Client
ClientInterface LegacyClass Delegation is used to bind an Adapter and an Adaptee (Legacy Class) Interface inheritance is use to specify the interface of the Adapter class. Adaptee (usually called legacy system) pre-exist the Adapter. Client Interface may be realized as an interface in Java. Request() ExistingRequest() adaptee Adapter Request().
21
Adapter for Scrubber in Lunar Module
Astronaut Scrubber CM_Cartridge Opening: Round Opening: Square ObtainOxygen() ScrubCarbonMonoxide() adaptee Round_To_Square_Adapter ObtainOxygen() Using a carbon monoxide scrubber (round opening) in the lunar module with square cartridges from the command module (square opening).
22
Modeling of the Real World
Design knowledge such as the adapter pattern complements application domain knowledge and solution domain knowledge Modeling of the real world leads to a system that reflects today’s realities but not necessarily tomorrow’s There is a need for reusable and extendable (“flexible”) designs.
23
Where are we? Object Design vs Detailed Design
System design vs object design Overview of object design activities Adapter pattern Types of Reuse Code reuse Interface reuse Class reuse Whitebox and blackbox reuse Object design leads also to new classes Implementation vs Specification Inheritance Inheritance vs Delegation Class Libraries and Frameworks
24
Reuse of Code I have a list, but the customer wants to have a stack
The list offers the operations Insert(), Find(), Delete() The stack needs the operations Push(), Pop() and Top() Can I reuse the existing list? I am an employee in a company that builds cars with expensive car stereo systems Can I reuse the existing car software in a home stereo system?
25
Reuse of interfaces I am an off-shore programmer in Hawaii. I have a contract to implement an electronic parts catalog for Daimler How can my contractor make sure that I implement it correctly? I would like to develop a window system for Linux that behaves the same way as in Vista How can I make sure that I follow the conventions for Vista and not those of MacOS X? I have to develop a new service for cars, that automatically call a help center when the car is used the wrong way Can I reuse the help desk software that I developed for a company in the telecommunication industry?
26
Reuse of existing classes
I have an implementation for a list of elements of Typ int Can I reuse this list to build a list of customers a spare parts catalog a flight reservation schedule? I have developed a class “Addressbook” in a previous project Can I add it as a subsystem to my program which I purchased from a vendor (replacing the vendor-supplied address book)? Can I reuse this class in the billing software of my dealer management system?
27
Customization: Build Custom Objects
Problem: Closing the object design gap Develop new functionality Main goals: Reuse functionality already available Use design knowledge (from previous experience) Composition (also called Black Box Reuse) The new functionality is obtained by aggregation The new object with more functionality is an aggregation of existing objects Inheritance (also called White-box Reuse) The new functionality is obtained by inheritance. Problem formulation for customization Develop this new functionality as a set of operations of a new class or adapt an existing program to a new environment or a new customer. So the goal is to produce custom objects to close the object design gap.
28
Example of Composition
Requirements Analysis (Language of Application Domain) Incident Report Text box Menu Scrollbar Incident Report Object Design (Language of Solution Domain)
29
Other Reasons for additional Objects in Object Design
The implementation of algorithms may necessitate objects to hold values New low-level operations may be needed during the decomposition of high-level operations Example: EraseArea() in a drawing program Conceptually very simple Implementation is complicated: Area represented by pixels We need a Repair() operation to clean up objects partially covered by the erased area We need a Redraw() operation to draw objects uncovered by the erasure We need a Draw() operation to erase pixels in background color not covered by other objects. New objects are often needed during object design: Let’s take as an example: The EraseArea() operation in a drawing program. Conceptually it is very simple, the Implementation Is much more complicated
30
White Box and Black Box Reuse
White box reuse Access to the development artifacts (analysis model, system design, object design, source code) must be available Black box reuse Access to models and designs is not available, or models do not even exist Worst case: Only executables (binary code) are available Better case: A specification of the system interface is available.
31
Types of Whitebox Reuse
1. Implementation inheritance Reuse of Implementations 2. Specification Inheritance Reuse of Interfaces Programming concepts to achieve reuse Inheritance Delegation Abstract classes and Method Overriding Interfaces There is a third way, reuse by Generic classes: Reuse of data structures for different base types We don‘t cover this in this class
32
Why Inheritance? 1. Organization (during analysis):
Inheritance helps us with the construction of taxonomies to deal with the application domain when talking the customer and application domain experts we usually find already existing taxonomies 2. Reuse (during object design): Inheritance helps us to reuse models and code to deal with the solution domain when talking to developers Inheritance is a useful concept for two reasons
33
The use of Inheritance Inheritance is used to achieve two different goals Description of Taxonomies Interface Specification Used during requirements analysis Activity: identify application domain objects that are hierarchically related Goal: make the analysis model more understandable Used during object design Activity: identify the signatures of all identified objects Goal: increase reusability, enhance modifiability and extensibility Let us think about how we model, When we observation Modeling of the Real World, we notice that we identify existing objects. Modeling of the real world leads to a system that reflects today’s realities but not necessarily tomorrow’s, or the visionary Scenario that drives our analysis. Transition to next slide: “Inheritance is found either by specialization or generalization”
34
Example of using Inheritance for Taxonomy
Superclass: Car public class Car { public void drive() {…} public void brake() {…} public void accelerate() {…} } drive() brake() accelerate() playMusic() ejectCD() resumeMusic() pauseMusic() LuxuryCar Subclass: public class LuxuryCar extends Car { public void playMusic() {…} public void ejectCD() {…} public void resumeMusic() {…} public void pauseMusic() {…} }
35
Inheritance can be used during Analysis as well as during Design
Starting point is always the requirements analysis phase: We start with use cases We identify existing objects (“class identification“) We investigate the relationship between these objects; “Discovering associations“: general associations aggregations inheritance associations.
36
Discovering Inheritance Associations
To “discover“ inheritance associations, we can proceed in two ways, which we call specialization and generalization Generalization: the discovery of an inheritance relationship between two classes, where the sub class is discovered first. Specialization: the discovery of an inheritance relationship between two classes, where the super class is discovered first. The distinction is subtle and depends on who is discovered first, the super class or the sub class
37
Generalization First we find the subclass, then the super class
This type of discovery occurs often in science and engineering: Biology: First we find individual animals (Elefant, Lion, Tiger), then we discover that these animals have common properties (mammals). Engineering: What are the common properties of cars and airplanes?
38
Generalization Example: Modeling Vending Machines
The class CoffeeMachine is discovered first, then the class SodaMachine, then the superclass VendingMachine After the generalization there is often an opportunity for Restructuring: Why don‘t we move the methods totalReceipts, collectMoney(), makeChange(), dispenseBeverage() into the super class? totalReceipts numberOfCups coffeeMix collectMoney() makeChange() heatWater() dispenseBeverage() addSugar() addCreamer() CoffeeMachine
39
Generalizing often leads to Restructuring
Called Remodeling if done on the model level; called Refactoring if done on the source code level. totalReceipts collectMoney() makeChange() dispenseBeverage() VendingMachine numberOfCups coffeeMix heatWater() addSugar() addCreamer() CoffeeMachine cansOfBeer cansOfCola chill() SodaMachine totalReceipts numberOfCups coffeeMix collectMoney() makeChange() heatWater() dispenseBeverage() addSugar() addCreamer() CoffeeMachine VendingMachine
40
Specialization Specialization occurs, when we find a subclass that is very similar to an existing class Example: A theory postulates certain particles and events which we have to find Specialization can also occur unintentionally: Example (from Physics): The Quarks-Theory postulates the existence of certain particles. After the theory was formulated, people started seaching for those particles and found them (others are still being looked for). Typical occurence of specialization in software projects: Last year we finished a project, in which we developed a machine, that delivers coffee and tea with automatic detection of empty containers. In the new project we have to develop the same functionality for our candy machines. „Such a machine must be possible“. The film and the picture show an unintended specialization: The car, a Mercedes-Benz CLR (see that turns into an airplane during the 24 hour race aof Le Mans in 1999 ( In 1999 Peter Dumbreck momentarily shot to world prominence when he not only survived but walked away uninjured from a horrifying high speed incident during the Hours of Le Mans race when his #5 Mercedes-Benz CLR somersaulted into the woods at about 300 km/h. Some Images: benzCLR1.html (Images copyright by Frederic Le Floc‘h)
41
Which Taxonomy is correct for the Example in the previous Slide?
„ ...Once the forces lifting the car exceed those holding it to the ground the car will fly“ ( fly() Airplane drive() Car drive() Car fly() Airplane We want to model a car and it exhibits flying behavior. It actually shoud not be called Airplane, but just Object which has an additional public method fly() Unintended Specialization
42
Another Example of a Specialization
numberOfCups coffeeMix heatWater() addSugar() addCreamer() CoffeeMachine totalReceipts collectMoney() makeChange() dispenseBeverage() VendingMaschine cansOfBeer cansOfCola chill() SodaMachine CandyMachine is a new product. We design it as a sub class of the superclass VendingMachine A change of names might now be useful: dispenseItem() instead of dispenseBeverage() and dispenseSnack() bagsofChips numberOfCandyBars dispenseSnack() CandyMachine
43
Example of a Specialization (2)
numberOfCups coffeeMix heatWater() addSugar() addCreamer() dispenseItem() CoffeeMachine totalReceipts collectMoney() makeChange() VendingMaschine cansOfBeer cansOfCola chill() SodaMachine bagsofChips numberOfCandyBars CandyMachine Now we have the method dispenseItem in the superclass! It should be an abstract method, implemented by each of the subclasses
44
Meta-Model for Inheritance
Object Design Analysis activity Inheritance is used during analysis as well as during object design! This is often confusing for modeling novices Taxonomy Inheritance for Reuse Specification Inheritance Implementation Inheritance Inheritance detected by Inheritance detected by specialization generalization
45
Implementation Inheritance and Specification Inheritance
Also called class inheritance Goal: Extend an applications’ functionality by reusing functionality from the super class Inherit from an existing class with some or all operations already implemented Specification Inheritance Also called subtyping Inherit from a specification The specification is an abstract class with all the operations specified but not yet implemented.
46
Implementation Inheritance vs. Specification Inheritance
Implementation inheritance: The combination of inheritance and implementation The interface of the superclass is completely inherited Implementations of methods in the superclass ("Reference implementations") are inherited by any subclass Specification inheritance: The combination of inheritance and specification Implementations of the superclass (if there are any) are not inherited.
47
Example for Implementation Inheritance
A class is already implemented that does almost the same as the desired class Add() Remove() List Example: • I have a List, I need a Stack • How about subclassing the Stack class from the List class and implementing Push(), Pop(), Top() with Add() and Remove()? “Already implemented” Push () Pop() Stack Top() Inheritance is a generalization technique, in which the behavior of a superclass is shared by all its subclasses. Sometimes it is misused as an implementation technique. Question: Can you give me an example for unwanted behavior? Problem with implementation inheritance: The inherited operations might exhibit unwanted behavior Example: What happens if the Stack user calls Remove() instead of Pop()?
48
Delegation instead of Implementation Inheritance
Inheritance: Extending a Base class by a new operation or overwriting an operation Delegation: Catching an operation and sending it to another object Which of the following models is better? +Add() +Remove() List Stack +Push() +Pop() +Top() +Push() +Pop() +Top() Stack +Add() +Remove() List
49
Delegation Delegation is a way of making composition as powerful for reuse as inheritance In delegation two objects are involved in handling a request from a Client The Receiver object delegates operations to the Delegate object The Receiver object makes sure, that the Client does not misuse the Delegate object. delegates to Client Receiver Delegate calls
50
Comparison: Delegation vs Implementation Inheritance
☺ Flexibility: Any object can be replaced at run time by another one (as long as it has the same type) Inefficiency: Objects are encapsulated Inheritance ☺ Straightforward to use ☺ Supported by many programming languages ☺ Easy to implement new functionality in the subclass ☹ Inheritance exposes a subclass to the details of its parent class ☹ Any change in the parent class implementation forces the subclass to change (which requires recompilation of both).
51
Recall: Implementation Inheritance v. Specification-Inheritance
Implementation Inheritance: The combination of inheritance and implementation The interface of the super class is completely inherited Implementations of methods in the super class ("Reference implementations") are inherited by any subclass Specification Inheritance: The combination of inheritance and specification Implementations of the super class are not inherited Or the super class is an abstract class.
52
Abstract Operations and Abstract Classes
Abstract method: A method with a signature but without an implementation. Also called abstract operation Abstract class: A class which contains at least one abstract method is called abstract class UML Interface: An abstract class which has only abstract operations An interface is primarily used for the specification of a system or subsystem. The implementation is provided by a subclass or by other mechanisms.
53
Example of an Abstract Operation
VendingMaschine dispenseItem() must be implemented in each subclass. We do this by specifying the operation as abstract. Abstract operations are written in UML in italics. totalReceipts collectMoney() makeChange() dispenseItem() dispenseItem() numberOfCups coffeeMix heatWater() addSugar() addCreamer() dispenseItem() CoffeeMachine cansOfBeer cansOfCola chill() SodaMachine bagsofChips numberOfCandyBars CandyMachine
54
Rewriteable Methods and Strict Inheritance
Rewriteable Method: A method which allows a reimplementation In Java methods are rewriteable by default, i.e. there is no special keyword Strict inheritance The subclass can only add new methods to the superclass, it cannot over write them If a method cannot be overwritten in a Java program, it must be prefixed with the keyword final.
55
Strict Inheritance Superclass: Subclass: public class Car {
public final void drive() {…} public final void brake() {…} public final void accelerate() {…} } drive() brake() accelerate() playMusic() ejectCD() resumeMusic() pauseMusic() LuxuryCar Subclass: public class LuxuryCar extends Car { public void playMusic() {…} public void ejectCD() {…} public void resumeMusic() {…} public void pauseMusic() {…} }
56
Example: Strict Inheritance and Rewriteable Methods
help() not overwritable Original Java-Code: class Device { int serialnr; public final void help() {….} public void setSerialNr(int n) { serialnr = n; } } class Valve extends Device { Position s; public void on() { … } setSerialNr() overwritable This implementation overwrites the method setSeriennr() from class Device
57
Example: Overwriting a Method
Original Java-Code: class Device { int serialnr; public final void help() {….} public void setSerialNr(int n) { serialnr = n; } } class Valve extends Device { Position s; public void on() { … } } // class Valve New Java-Code : class Device { int serialnr; public final void help() {….} public void setSerialNr(int n) { serialnr = n; } } class Valve extends Device { Position s; public void on() { … public void setSerialNr(int n) { serialnr = n + s.serialnr; } } // class Valve This implementation overwrites the method setSeriennr() from class Device
58
UML Class Diagram Device Device - int serialnr - int serialnr
+ setSerialNr(int n) Valve -Position s + on() + setSerialNr() Device - int serialnr +setSerialNr(int n) Valve - Position s +on()
59
Overwriteable Methods: Usually implemented with Empty Body
class Device { int serialnr; public void setSerialNr(int n) {} } class Valve extends Device { Position s; public void on() { ….. public void setSerialNr(int n) { seriennr = n + s.serialnr; } // class Valve I expect, that the method setSerialNr()will be overwritten. I only write an empty body The empty body is also called stub Overwriting of the method setSerialNr() of Class Device
60
Bad Use of OverwritingMethods
One can overwrite the operations of a superclass with completely new meanings Example: Public class SuperClass { public int add (int a, int b) { return a+b; } public int subtract (int a, int b) { return a-b; } } Public class SubClass extends SuperClass { public int add (int a, int b) { return a-b; } public int subtract (int a, int b) { return a+b; } We have redefined addition as subtraction and subtraction as addition!! Programming languages do not forbid such constructs. But they violate our intuitive understanding of addition, and are thus a bad use of inheritance and specialization.
61
Bad Use of Implementation Inheritance
We have delivered a car with software that allows to operate an on-board stereo system A customer wants to have software for a cheap stereo system to be sold by a discount store chain Dialog between project manager and developer: Project Manager: „Reuse the existing car software. Don‘t change this software, make sure there are no hidden surprises. There is no additional budget, deliver tomorrow!“ Developer: „OK, we can easily create a subclass BoomBox inheriting the operations from the existing Car software“ „And we overwrite all method implementations from Car that have nothing to do with playing music with empty bodies!“ We have delivered a car with software for a very good Stereosystem sold by DaimlerChrsyler dealers. The implementation was very timeconsuming and costly. We are asked by a new customer to develop a cheap stereo-system, to be sold by chap discount department stores
62
What we have and what we want
New Product! ExistingProduct!
63
What we do to save money and time
Existing Product: public class Auto { public void drive() {…} public void brake() {…} public void accelerate() {…} public void playMusic() {…} public void ejectCD() {…} public void resumeMusic() {…} public void pauseMusic() {…} } New Product: public class Boombox extends Auto { public void drive() {}; public void brake() {}; public void accelerate() {}; }
64
Contraction Contraction: Implementations of methods in the super class are overwritten with empty bodies in the subclass to make the super class operations “invisible“ Contraction is a special type of inheritance It should be avoided at all costs, but is used often.
65
Contraction should be avoided
A contracted subclass delivers the desired functionality expected by the client, but: The interface contains operations that make no sense for this class What is the meaning of the operation brake() for a BoomBox? The subclass does not fit into the taxonomy A BoomBox ist not a special form of Auto The subclass violates Liskov's Substitution Principle: I cannot replace Auto with BoomBox to drive to work.
66
Revised Metamodel for Inheritance
Object Design Analysis activity Taxonomy Inheritance for Reuse This is the final metamodel for modeling inheritance. Today we have added strict inheritance and contractions as two additional ways to use implementation inheritance: We identified strict inheritance as a good citizen, and if used this way, then implementation inheritance is a good thing. And we have shown that contract is a bad idea, because it leads to unmaintainable systems and unpredictable behavior. Specification Inheritance Implementation Inheritance Inheritance detected by Inheritance detected by specialization generalization Strict Inheritance Contraction
67
Frameworks A framework is a partial application that can be specialized to produce custom applications The key benefits of frameworks are reusability and extensibility: Reusability leverages of the application domain knowledge and prior effort of experienced developers Extensibility is provided by methods which can be overwritten by the application to extend the framework. Frameworks are targeted to particular technologies, such as data processing or cellular communications, or to application domains, such as user interfaces or real-time avionics. Hook methods systematically decouple the interfaces and behaviors of an application domain from the variations required by an application in a particular context.
68
Classification of Frameworks
Frameworks can be classified by their position in the software development process: Infrastructure frameworks Middleware frameworks Frameworks can also be classified by the techniques used to extend them: Whitebox frameworks Blackbox frameworks Framework classification according to the software development process: ???? Frameworks are targeted to particular technologies, such as data processing or cellular communications, or to application domains, such as user interfaces or real-time avionics.
69
Frameworks in the Development Process
Infrastructure frameworks aim to simplify the software development process Used internally, usually not delivered to a client Middleware frameworks are used to integrate existing distributed applications Examples: Java RMI, CORBA, WebObjects, WebSphere. Enterprise application frameworks are application specific and focus on domains Example of application domains: telecommunications, avionics, environmental modeling, manufacturing, financial engineering, enterprise business activities. Infrastructure frameworks aim to simplify the software development process System infrastructure frameworks are used internally within a software project and are usually not delivered to a client. Middleware frameworks are used to integrate existing distributed applications and components. Examples: MFC, DCOM, Java RMI, WebObjects, WebSphere, WebLogic Enterprise Application [BEA]. Enterprise application frameworks are application specific and focus on domains Example domains: telecommunications, avionics, environmental modeling, manufacturing, financial engineering, enterprise business activities.
70
White-box and Black-box Frameworks
White-box frameworks: Extensibility is achieved through inheritance and dynamic binding Existing functionality is extended by subclassing framework base classes and overwriting specific methods designed to be overwritten(so-called hook methods) Black-box frameworks: Extensibility is achieved by defining interfaces for components that can be plugged into the framework. Existing functionality is reused by defining components that conform to a particular interface These components are integrated with the framework via delegation. Whitebox frameworks: Extensibility achieved through inheritance and dynamic binding. Existing functionality is extended by subclassing framework base classes and overriding predefined hook methods Often design patterns such as the template method pattern are used to override the hook methods. Blackbox frameworks: Extensibility achieved by defining interfaces for components that can be plugged into the framework. Existing functionality is reused by defining components that conform to a particular interface These components are integrated with the framework via delegation.
71
Class libraries vs. Frameworks
Class Library: Provide a smaller scope of reuse Is less domain specific Class libraries are passive; there is no constraint on the flow of control Framework: Classes cooperate for a family of related applications. Frameworks are active; they affect the flow of control. In practice, developers often use both: Frameworks often use class libraries internally to simplify the development of the framework. Framework event handlers use class libraries to perform basic tasks (e.g. string processing, file management, numerical analysis…. )
72
Components vs. Frameworks
Self-contained instances of classes Plugged together to form complete applications Can even be reused on the binary code level The advantage is that applications do not have to be recompiled when components change Framework: Often used to develop components Components are often plugged into blackbox frameworks. Components: Self-contained instances of classes Plugged together to form complete applications. Blackbox that defines a cohesive set of operations, Can be used based on the syntax and semantics of the interface. Components can even be reused on the binary code level. The advantage is that applications do not always have to be recompiled when components change. Frameworks: Often used to develop components Components are often plugged into blackbox frameworks.
73
Documenting the Object Design
Object design document (ODD) = The Requirements Analysis Document (RAD) plus... … additions to object, functional and dynamic models (from the solution domain) … navigational map for object model … Specification for all classes (use Javadoc) ODD Management issues Update the system models in the RAD? Should the ODD be a separate document? Who is the target audience for these documents (Customer, developer?) If time is short: Focus on the Navigational Map and Javadoc documentation? ODD Template:
74
Documenting Object Design: ODD Conventions
Each subsystem in a system provides a service Describes the set of operations provided by the subsystem Specification of the service operations 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 JavaDoc and Contracts for the specification of service operations Contracts are covered in one of the next lectures. Each subsystem in a system provides a service (see Chapters 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 JavaDoc for the specification of service operations.
75
Package it all up Pack up object design into discrete units that can be edited, compiled, linked, reused Construct physical modules Ideally use one package for each subsystem But system design might not be good enough for packaging Two design principles for packaging Minimize coupling: Classes in client-supplier relationships are usually loosely coupled Avoid large number of parameters in methods to avoid strong coupling (should be less than 4-5) Maximize cohesion: Put classes connected by associations into one package.
76
Packaging Heuristics Each subsystem service is made available by one or more interface objects within the package Start with one interface object for each subsystem service Try to limit the number of interface operations (7+-2) If an interface object has too many operations, reconsider the number of interface objects If you have too many interface objects, reconsider the number of subsystems Interface objects vs Java interface: Interface object: Used during requirements analysis, system design, object design. Denotes a service or API Java interface: Used during implementation in Java (May or may not implement an interface object).
77
Lectures on Mapping Models to Code
Summary Object design closes the gap between the requirements and the machine Object design adds details to the requirements analysis and makes implementation decisions Object design activities include: Identification of Reuse Identification of Inheritance and Delegation opportunities Component selection Interface specification (Next lecture) Object model restructuring Object model optimization Object design is documented in the Object Design Document (ODD). Lectures on Mapping Models to Code
78
Backup Slides
79
Reuse Main goal: Composition (also called Black Box Reuse)
Reuse knowledge from previous experience to current problem Reuse functionality already available Composition (also called Black Box Reuse) New functionality is obtained by aggregation The new object with more functionality is an aggregation of existing components Inheritance (also called White-box Reuse) New functionality is obtained by inheritance. Three ways to get new functionality: Implementation inheritance Interface inheritance Delegation
80
Example: Framework for Building Web Applications
WebObjects WebBrowser StaticHTML WOAdaptor WebServer WoRequest Template WebObjectsApplication WORequest EOF RelationalDatabase
81
Customization Projects are like Advanced Jigsaw Puzzles
The whimsies are generally related to the subject of the image, e.g. a wooden jigsaw puzzle of your favorite pet would feature animal whimsies, a wooden jigsaw puzzle of your garden would feature plants, tools, even a gardener leaning on a spade and so on. There are up to 15 whimsies per puzzle. It's no surprise, therefore, that Wentworth puzzles seem to be achieving a unique, cult-like status throughout the world; rather unusual for jigsaws, don't you think? Wentworth wooden jigsaw puzzles are even becoming collectors items, changing hands for significantly higher prices than the original purchase prices. These puzzles are so totally absorbing, they are the perfect antidote to the stresses and strains of every day living. All Wentworth puzzles are cut from a wooden composite called Medite™. This is an FSC (Forest Stewardship Certified) registered product and will provide enduring pleasure to generations of enthusiasts. Design Patterns! Source
82
Application Domain vs Solution Domain Objects
Requirements Analysis (Language of Application Domain) Subject Observer * observers subscribe(subscriber) unsubscribe(subscriber) notify() update() Object Design (Language of Solution Domain) ConcreteSubject state getState() setState() ConcreteObserver observeState update() Object design introduces new objects! Here is an example of a generic pattern, showing a subject observed by many observers (the observer pattern)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.