Object-oriented programming concepts and component...
Transcript of Object-oriented programming concepts and component...
Object-orientedprogrammingconceptsandcomponentsystemsLenaBuffoni/TDDD05
Anobject…
APRIL 3, 2017 2
• is a unit of instantiation, it has a unique identity
• may have state and this can be externally observable
• encapsulates its state and behavior
• reusable
Objects can be thought of as a typing system.
• Is everything an object?
Whatisacomponent?
APRIL 3, 2017 3
• “A software component is a unit of composition with contractually specified interfaces and explicit context dependencies only. A software component can be deployed independently and is subject to composition by third parties.”
• Object => Component?• Component => Object ?
Whitebox vs.Blackbox
APRIL 3, 2017 4
Robustnessvs Leanness
APRIL 3, 2017 5
Robustness (ex: multi-platform, flexible, configurable…)
vs.
Leanness (ex: lightweight…)
What a component is and is not
a component designer has a choice. Increasing the context dependencies usu-ally leads to leaner components by means of reuse, but also to smaller markets.Additionally, higher vulnerability in the case of environmental evolution mustbe expected, such as changes introduced by new versions. Increasing thedegree of self-containedness reduces context dependencies, increases themarket, and makes the component more robust over time, but also leads to“fatter” components. Figure 4.1 illustrates the optimization problem resultingfrom trading leanness against robustness.
The effective costs of making a component leaner, compared with making itmore robust, need to be estimated to turn the qualitative diagram of Figure4.1 into a quantitative optimization problem. There is no universal rule here.The actual costs depend on factors of the component-producing organizationand of the target markets for the component. The markets determine the typi-cal deployment environment and client expectations, including component“weight” and expected lifetime.
Note that it is not just coincidence that Figure 4.1 and Figure 1.1 (p. 6) areso similar. The discussion in this section focused on the “outsourcing” of partsof a component. In contrast, the discussion in Chapter 1 concentrated on theoutsourcing of parts of a system – that is, the outsourcing of components. Theformer is about reuse across components, whereas the latter is about reuse ofcomponents.
Standardization and normalization
The “sweet spot” of the optimization problem introduced above can beshifted toward leaner components by improving the degree of normalizationand standardization of interface and component worlds. The more stable andwidely supported a particular aspect is, the less risky it becomes to make it aspecified requirement for a component. Context dependencies are harmlesswhere their support is ubiquitous. For example, only 50 years ago it would
4.2
46
Figure 4.1 Opposing forcefields of robustness (limited context dependence) and leanness (limited“fat”), as controlled by the degree of reuse within a component.
0 100
Leanness Robustness
% reuse (“outsourcing”)
8557 Chapter 4 p33-48 3/10/02 10:31 PM Page 46
Standardizationandnormalization
APRIL 3, 2017 6
• Increases leanness of components• Improves interoperabilityEx: TCP/IP standard, we reduce the kinds of bolts in use …• Generic vs. domain specific
standardizationEx: general UML standard vs. specific UML-RT standard
Interfaces
APRIL 3, 2017 7
• A point of interaction between the component and the environment
InterfacesinUMLAPRIL 3, 2017 8
interface Animal {
public void eat();public void sleep();
}
InterfacesinJava
GUI
Directvs. Indirectinterfaces
APRIL 3, 2017 9
• Direct (procedural) interfaces = implements + provided directly by a component corresponding
to interfaces of traditional libraries. + definition & implementation belong to one
component. • Indirect(object) interfaces = has a
+ provided by objects implemented by a component, corresponding to object interfaces.
+ definition & implementation might sit in different components.
Example
APRIL 3, 2017 10
Attention: version checking in indirect interfaces is tricky!
Components, interfaces, and re-entrance
5.1.2 VersionsIn a component world, versions of components can be prolific. For example,many vendors may provide various “upwards-compatible,” enhanced versionsof a successful component. Traditional version management – often based onthe assignment of major and minor version numbers – assumes that the ver-sions of a component evolve at a single source. In a free market, the evolutionof versions is more complex and management of version numbers can becomea problem in its own right.
A subtle aspect of versioning arises when moving from direct to indirectinterfaces – that is, to object interfaces. With direct interfaces it suffices tocheck versions at bind time, which is when a service is first requested. As dis-cussed above, indirect interfaces couple arbitrary third parties. In a versionedsystem, care must be taken to avoid indirect coupling of parties that are ofincompatible versions. For example, a client originally requesting a service maybe capable of working with version 1 of that service. Once it holds an objectreference, it may pass the reference on to another component. However, thelatter component might require version 2 of the service. Unless versions arechecked in every place where an object reference crosses component bound-aries, version checking is not sound.
Few component infrastructures proposed so far address the component ver-sioning problem properly. The goal is to ensure that older and newercomponents are either compatible or clearly detected as incompatible. Thegeneral strategy is to support a sliding window of supported versions. That is,ideally, once established compatibility is stable until an act of deprecation andfinally removal ends compatibility cleanly for good.
One possible approach is to insist on immutable interface specifications.Instead of trying to maintain the complex compatibility relationship amongvarious versions of interfaces, each interface, once published, is frozen andnever changed again. Supporting multiple versions is then equivalent to sup-porting multiple interfaces. An outdated interface is simply no longer
52
Figure 5.1 Example of direct and indirect interfaces.
GrammarChecker
Grammar-checking component
WordProcessor
Wordprocessing component
«interface»ICheckGrammar
TextServices
Text services mediator component
2
143
“has a”
implements
8557 Chapter 5 p49-82 3/10/02 10:32 PM Page 52
Designbycontract
APRIL 3, 2017 11
• Between a client and a provider
• What the client needs to do to use the interface.
• What the provider has to implement to meet the services promised by the interface.
Pre,postconditionsandinvariants
APRIL 3, 2017 12
• precondition A condition that must be true of the parameters of a method and/or data members, if the method is to behave correctly, PRIOR to running the code in the method.
• postcondition A condition that is true AFTER running the code in a method.
• class invariant A condition that is true BEFORE and AFTER running the code in a method (except constructors and destructors)
Whatelseshouldbeconsideredinacontract?
APRIL 3, 2017 13
• Extra functional (e.g. performance) requirements• Reliance on implicit/undocumented features
Examplestackimplementation
APRIL 3, 2017 14
• What actions should be possible with a stack?– push() add an element to the top– pop() remove an element to the top– size() return the number of elements in stack– isEmpty() returns true, if stack is empty (size is 0)– peek returns the top element, without removing it
Invariants
APRIL 3, 2017 15
• first points to NULL or a valid node• first points to the top of the stack• each node's next pointer points to a node or a valid
node• the number of nodes is equal to the size data member
push(stringstr )
APRIL 3, 2017 16
• precondition true• postcondition
size == size' + 1 AND list == str + list'.
ADA:procedure PUSH(S: in out STACK; E: in ELEM) is
begin if S.INDEX = SIZE then raise OVERFLOW; endif; S.INDEX := S.INDEX + 1; S.SPACE(S.INDEX) := E;
end PUSH;
Defensive programming?
OCL(ObjectConstraintLanguage)
APRIL 3, 2017 17
• Part of the UML standard Formal Specification Language
• Standardized formal semantics from OCL 2.0 onwards
OCLexample:Invariant
APRIL 3, 2017 18
Person
name:Stringage:int
<<query>>getName():Stringbirthday()
Vehicle
Car Bike
ownershipowner1
fleet0..*
Minimal age for an owner?
OCLexample:Invariant
APRIL 3, 2017 19
Person
name:Stringage:int
<<query>>getName():Stringbirthday()
Vehicle
Car Bike
ownershipowner1
fleet0..*
“A vehicle owner must be at least 18 years old”: context Vehicleinv: self. owner. age >= 18
“A car owner must be at least 18 years old”: context Carinv: self.owner.age >= 18
ContractConformance
APRIL 3, 2017 20
• Contracts may be modified from version to version • What will be affected if the implementation of an
interface is revised from one version to another? – Respects the old contract by not breaking any old
clients– Breaks some old client(s) and results in a failure
of services
ContractConformance
APRIL 3, 2017 21
• Contract conformance – Pre-condition: Overriding method must demand
the same or less from its client – Post-condition: Overriding method must promise
the same or more to its client – Exceptions: overriding method must not throw
any exceptions overridden doesn’t
Partialorcompletecorrectness?
APRIL 3, 2017 22
• Simple pre- and postconditions => Partial correctness
• A partially correct operation either terminates correctly or does not terminate at all.
• The requirement that an operation should also eventually terminate leads to total correctness.
Types,subtypes,andtypechecking
APRIL 3, 2017 23
• Types can be viewed as simplified contracts
• Safety by construction – viability of components
• Typing polymorphism : subtypes
Polymorphism
APRIL 3, 2017 24
Shape
Rectangle Triangle
Polymorphism is the ability of something to appear in multiple forms, depending on context, and the ability of different things to appear the same in a certain
context.
When can we replace one sub-type for another?
Liskov's Substitution Principle
CovarianceandContravariance
APRIL 3, 2017 25
• Covariance:New parameter types, return value types, or exception types of replacing methods are proper subtypes (more specific) of the corresponding original types in the replaced method.
• Contravariance:New parameter types, return value types, or exception types of replacing methods are proper supertypes (more general) of the corresponding original types in the replaced method.
• Invariance:New parameter types etc. are of exactly the same type as in the replaced method.
Covariance:simpletypes
APRIL 3, 2017 26
public class Animal{}public class Mammal extends Animal { }public class Tiger extends Mammal { }
Mammal m = new Tiger();Animal a = m;Tiger t = a;
OKOKNOT OK
Animal
Mammal
Tiger
Covariance&Contravariance:methods
APRIL 3, 2017 27
class Super{void doSomething(String parameter)
}class Sub extends Super{
void doSomething(Object parameter)}
Contravariance
class Super {Object getSomething(){}
}class Sub extends Super {
String getSomething() {}}
Covariance
Invariance:Lists
APRIL 3, 2017 28
List<Mammal> mammals = new List<Tiger>(); List<Animal> animals = mammals; List<Tiger> tigers = animals;
mammals.add(new Dog());Tiger rrr = tigers.get(0);
FragileBaseClassProblem
APRIL 3, 2017 29
• How does a class evolve over time?
• Can a base class be updated without affecting the system?
Thesyntacticfragilebaseclassproblem
APRIL 3, 2017 30
• Is inheritance all that safe?• What happens when we edit a base class?class A{
protected int x;protected void m(){x++;}
protected void n(){x++;}}
class B extends Base{protected void m(){
n();}
}
class A{protected int x;protected void m(){x++;}
protected void n(){m();}}
A gets updated
ThesemanticfragilebaseclassproblemAPRIL 3, 2017 31
DevelopsalibrarycontainingbaseClassA
WritesclassBinheritingfromA
UpdatesA(back-wardscompatible)
Reinstallslibrary,relinks,runsapp
Recompilestheapplication
Application crashes
Developer A Developer B
All Ok!
The release to release compatibility problem
Multiple-inheritance
APRIL 3, 2017 32
UniversityMember
Teacher Student
PhDStudent
Diamond inheritance principle
Teacher and Student have different re-definitions of the method roomBookingRights();Which one does PhD Student inherit?
Whydowewantmultipleinheritance?APRIL 3, 2017 33
Animals
Mammals Birds Reptiles
Classifying animals
APRIL 3, 2017 34
Animals
Mammals Birds Reptiles
Nocturnal Diurnal
Diurnality
APRIL 3, 2017 35
Animals
Mammals Birds Reptiles
And now carnivore/herbivore? =>HerbivoreNocturnalMammals, …
DiurnalMammals Nocturnal
Mammals
DiurnalBirds
NocturnalBirds
…
Avoiding Multiple Inheritance
Multiple-inheritance&mixins
APRIL 3, 2017 36
• Multiple inheritance can be used in a particular style called mixin inheritance (Bracha and Cook, 1990).
• A class inherits interfaces from one superclass and implementations from several superclasses
• Each focusing on distinct parts of the inherited interface.
• The inherited classes are called mixins, as they are used to mix implementation fragments into a class.
Summary
APRIL 3, 2017 37
• Different structuring concepts: objects, components, interfaces
• The design process is a constant tradeoff: flexibility vs. robustness, simplicity vs. completeness
• Promise more – get more• All technologies have limits and pitfalls