Abstraction Design fundamentals in OO Systems Tool for abstraction: object Object structure: properties and values for those properties operations to query and update those properties We refer to the collection of values of all properties of an object as the state of the object. System structure: network of collaborating objects which together solves problem. Fundamental Software Development Principles Cohesion: A module should model one well defined concept; its functionality must only deal with supporting the concept being modeled. Coupling : a module s collaborators should be small in number and it should interact through a well defined interface. Tools for Design: Inheritance and Composition Inheritance strong coupling between components allows modification of components being reused Making a new class involves programming static relationship Composition powerful reuse technique, difficult to understand by examining static program text. Composition can be changed at run-time 1
Delegation Composed object uses its components to implement its interface. Sometimes a composed object receives a messages which it forwards to one of its components for execution. This is called delegation. It is a misused term, it should be called forwarding or consulting Uses of inheritance Identifying common functionality among a collection of classes providing an implementation of a method in an abstract class providing an alternative implementation refining the implementation of a method extending functionality of an existing class Concrete classes, abstract classes, interfaces When should we subclass, when should we compose? When to use an abstract class, when to use an interface? Abstract classes To model a generalized object Specification of an abstract class ought to be stable Should factor out common implementation details of its subclasses Mechanism used to exploit polymorphism Abstract classes can be extended without breaking running code. 2
Interfaces Model to generalize functionality they are by definition abstract, no aspects of its implementation is fixed. A way to multiple inheritance: A class can implement one or more interfaces Allows for a more generalized used of polymorphism Interfaces cannot be modified They are the key to pluggability Interfaces and the software lifecycle Design: serve as a stabilizing element in the specification and implementation of classes Implementation: compiler checks that class implementing interface fullfills contract Integration: well-established interfaces are glue for composed classes and subsystems Testing: logical errors are limited to a subset of methods Inheritance and composition Advantages of inheritance: code reuse polymorphism extension of an existing class dis-advantages of inheritance superclass and subclass are strongly coupled; changes to superclass affect suclass, and subclass cannot change specification of superclass methods It s a static feature Inheritance and composition Advantages of composition code reuse as black box reuse can change composed object s core class at runtime; ie, it s a dynamic property of object Supports stronger encapsulation than inheritance. Changes to core class does not affect specification of composed class. And vice-versa, changes to composed class do not affect core class. 3
Inheritance and composition Dis-advantages of composition lose polymorphism!!! Can gain it back: compose with interfaces and have core classes implement those interfaces Mis-uses of inheritance To model roles To provide implementation alternatives to a given abstraction Consequences: class explosion Inheritance and composition Favor composition over inheritance Inheritance should not be used for code reuse or to take advantage of polymorphism It is harder to maintain inheritance based code than composition based code. Inheritance and composition Use inheritance when the complete interface of the superclass applies to the subclass candidate there is a permanent is-a relationship superclass is stable. For specialization 4
Inheritance and composition Composition can be used some features of core class are irrelevant, ie, new class is not a true functional subtype to provide implementation to some specific functionality. high proportion of code of base class need to be rewritten Use composition to extend functionality by delegating to more appropriate objects. Inheritance and composition Interfaces can be used to maintain separation of between specification and implementation to provide reuse and polymorphism across hierarquies Clients/Servers v.s. Abstraction/Implementation Servers present abstractions in its highest form to the client: interfaces Reduces coupling of clients to implementation choices. It raises clients code reuse. Hence: clients use interfaces to declare objects Servers specify parameters via interfaces Update of object s class Example: modeling with inheritance Worker Fixed Sales Hourly 5
Update of object s class transmute problem: How to update an object from one type of subclass to another? In business terms: how to promote a worker? via copying & delete Update of object s class What changes among the workers is the method used to compute salary. Define class Salary with 3 subclasses Define class Worker with salary() query. Worker s implementation uses private Salary component initialized in the constructor and used to compute salary() With composition: use simple assignment to component being updated. Worker Improved design Example Need to model student implements Worker Has-a Salary Later on need to model PT, FT student Student Fixed Sales Hourly PT FT 6
Example Later own, need to consider graduate student Student Later on...add student worker Student PT FT Grad PT FT Grad PTGrad FTGrad PTGrad FTGrad AGGGGHHHHHHHHHHHHHHHHH!! Alternative Example: Account class Define : Student with subclasses undergrad, GradStudent Define: Status with subclasses PT, FT Define: Worker with subclasses FTW, PTW Now based on student we compose to get a student who is part-time and ft worker a grad student full time and part time worker Designed to include customer information: name address account identification number 7
Example: Account class Design not cohesive: two abstractions customer information account Cohesion Limitations introduced due to the one-toone correspondence of the two abstractions one customer with several accounts join accounts Class specialization Composition Account Account * 1..* owner Customer Cash Acc Porfolio Ac Individual Institution Composing on the two dimensions: class explosion. One possible solution: multiple inheritance. More trouble that what solves. Problem: inheritance diamond. Cash Acc Porfolio Ac Individual Institutional 8
Inheritance vs composition Examples: Sensor, remote Sensor Subclasses of Thread, not a good choice Subclasses of Observable Rules to achieve cohesion An attribute should have a single value and not have structure (repeating groups) Account with many different currencies balance has as value list of <currency,balance> An attribute should describe an instance of its containing class customer name, address, etc do not describe an Account instance An example First solution Design a Button class to control a lightbulb software to reside on table lamp Somehow fact that user has pressed button is communicated to software Button contains LightBulb Not reusable Reusable 9
Second solution Third solution Button Button contains ButtonServer LightBulbButton contains LightBulb PumpButton LightBulb Reusable Not so Reusable Forth solution Trade-off Evaluation Second Solution : less code but Button contains ButtonServer locks the relationship between a Button object and object it controls Fourth solution : more flexible. Reusable LightServer contains LightBulb Reusable Any Button object can be used to control any derivative of ButtonServer. allows many different objects to be controlled by the same Button at different times. 10
Engineering Tradeoff Choice of solution to use involves an engineering tradeoff. Fourth solution: flexibility V.S. speed and complexity overhead Second solution resource frugal V.S. much less flexibility Design 1 is the simplest; simplicity of design does not necessarily relate simplicity of maintenance, possibility or simplicity of reuse. in order to create a design that is maintainable and reusable, some conceptual effort must be applied. Artifacts for abstraction Cost to apply object-oriented design. Good object-oriented design will generally be more complex than procedural design Extra complexity: infrastructure to manage dependencies Don t begrudge extra complexity. Payoff maintainance reuse At syntactic and semantic level: classes, objects At design level: Patterns Reusable tried-and-true design there is a well-defined context for problem, some variences may occur there have been several occurrences of it possibly under different guises (>= 3) presented in a strict codify form 11
Cohesion Abstraction unit model one concept functionality to support concept only Design goal: minimize features A class with high cohesion : maintains localizes protects features necessary to perform primary role Cohesion Provide enough features to support role This implies: not adding derived functionality that can be perform with them This enables superimposed layers to control components in different ways Goal: high cohesion of components Coupling module s collaborators should be small in number should interact through well defined interface Unit minimizes demands on environment Goal: low coupling and type of coupling Representational coupling Should not depend on representation or computational detail of another one Addresses: interchangeable parts multiple representations prototype evolution system evolution performance tuning Extensibility External components Standarization Testability Frameworks 12
Value coupling Classes should be written so that operations are independent of particular values when special values occur, use classes to classify and manipulate them(state pattern) Subclass coupling Client refers to a subclass object through subclass reference rather than superclass reference. In Java use of abstract classes and interfaces to raise reuse opportunity Code coupling (Control?) The definition of concrete operations should be decoupled from the context in which they are employed Sequential vs. concurrent execution Example: how to get an item to a list vs when to get it. Should be possible to define how to get it for either situation Inheritance Coupling this is a compile-time binding cannot be discarted at execution time This is the old problem: inheritance vs. composition if you compose: may design zero or more instances of the object can set/change its value at run-time. 13
Rise of Coupling in OO An OO system is a network of interactive objects interaction between objects creates the coupling (dependence) the interaction results due to implementation of relations among the objects Thus coupling in OO system is necessary, but it creates dependencies among classes, components, subsystems activity of good analysis and design: management of dependencies What s wrong with dependencies? End result due to lack of management of these dependencies: Brittle software: changes propagate beyond expected boundaries OR Hard software: it does not respond to changes Opposite this state of affairs: units of abstraction localize possible changes and abstraction units are change-responsive: flexible How to get flexible abstractions? Actively design for that characteristic Start with cohesion & coupling of abstractions look for : high cohesion, low / kind of coupling identify and abstract/encapsulate what varies Test flexibility of your abstractions produce an active list of possible changes to measure flexibility against. NNB Static coupling Binding of Coupling established at compilation time need definitions of dependents for compilation Dynamic coupling two classes are dynamically coupled if their instances call methods of one or the other at run-time 14
Transitivity in Dependencies If A depends on B, B depends on C, hence A depends on C Coupling Best practices Identify subsystems closed for changes reused as a whole well-defined purpose Reduce static coupling between different subsystems classes. Pay special attention to transitive coupling Reduce dynamic coupling Software Principles Information Hiding principle:.a client does not need to know how a module (system) work to use it..a client should not be allowed to extend the system knowing how the system works. Software Continuity principle: small changes in the specification should produce small changes in the implementation of the module (system) Software Principles. Cont... The OCP (Open-Closed Principle), The LSP (Liskov substitution Principle), The DIP (Dependency Inversion Princ), The ISP (Interface Segregation Principle), The RREP (Reuse/Release Equivalency principle), The CCP (Common Closure Principle), 15
Software Principles. Cont... The CRP (Common Reuse Principle) The ADP (Acyclic Dependencies Principle), The SDP (Stable Dependencies Principle) The SAP (Stable Abstractions Principle) The LoD (Law of Demeter) 16