12TraitsClassboxes.ppt

Download Report

Transcript 12TraitsClassboxes.ppt

12. Traits and Classboxes
ST — Understanding Classes and Metaclasses
Roadmap
>
>
>
>
>
>
>
Problems with Inheritance
Traits
Refactoring Collections with Traits
Traits in Squeak
Classboxes
Traits and Classboxes
Ongoing Research
© Oscar Nierstrasz
Selected material courtesy of Nathanael Schaerli and Alexandre Bergel
12.2
ST — Understanding Classes and Metaclasses
Roadmap
>
>
>
>
>
>
>
Problems with Inheritance
Traits
Refactoring Collections with Traits
Traits in Squeak
Classboxes
Traits and Classboxes
Ongoing Research
© Oscar Nierstrasz
12.3
ST — Understanding Classes and Metaclasses
How Can We Implement This?
Visual
Bordered
Bordered
Circle
Rectangle
Rectangle
BorderedCircle
BorderedRectangle
Bordered
© Oscar Nierstrasz
Bordered
12.4
ST — Understanding Classes and Metaclasses
Alternative Approaches
Single inheritance leads to code duplication
> Alternatives:
>
— Multiple inheritance
— Mixins
© Oscar Nierstrasz
12.5
ST — Understanding Classes and Metaclasses
Problems with Multiple Inheritance
>
Multiple Inheritance problems
— No access to super (ill-defined)
–
Workarounds are clumsy or lead to duplicated code
— Complex rules for resolving conflicts (esp. state)
— Fragile hierarchy
–
Changes may impact distant classes
Ducasse, et al., "Traits: A Mechanism for fine-grained Reuse", TOPLAS 2006
© Oscar Nierstrasz
12.6
ST — Understanding Classes and Metaclasses
Problems with Mixins
>
Mixin problems
— Dispersal of glue code
–
–
Conflict resolution is sensitive to mixin composition order
Composing entity has no control!
— Fragile hierarchy
–
Changes may impact distant classes
Ducasse, et al., "Traits: A Mechanism for fine-grained Reuse", TOPLAS 2006
© Oscar Nierstrasz
12.7
ST — Understanding Classes and Metaclasses
Roadmap
>
>
>
>
>
>
>
Problems with Inheritance
Traits
Refactoring Collections with Traits
Traits in Squeak
Classboxes
Traits and Classboxes
Ongoing Research
© Oscar Nierstrasz
12.8
ST — Understanding Classes and Metaclasses
Traits
Circle
Rectangle
Polygon
Traits =
Building Blocks
Circle
Rectangle
Rectangle
+
Colored
Polygon
Colored
Circle
© Oscar Nierstrasz
+
Colored
+
Bordered
Bordered
12.9
ST — Understanding Classes and Metaclasses
Traits in a nutshell
>
Traits are parameterized behaviors
— Traits provide a set of methods (
— Traits require a set of methods (
— Traits do not specify any state
)
)
TCircle
area
bounds
circumference
diameter
hash
© Oscar Nierstrasz
radius
radius:
center
center:
12.10
ST — Understanding Classes and Metaclasses
Using Traits to Compose Classes
Class = Superclass + State + Traits + Glue methods
Visual
ColoredCircle
rgb
radius
center
The composing class
retains control of the
composition.
TCircle
TColor
© Oscar Nierstrasz
12.11
ST — Understanding Classes and Metaclasses
Composition Rules
1. Class methods take precedence over trait methods
2. Composition is commutative
— Conflict resolution is always explicit
3. Flattening Property
— Trait methods have no special semantics
© Oscar Nierstrasz
12.12
ST — Understanding Classes and Metaclasses
Rule 1: Precedence of Class Methods
ColoredCircle
radius
radius
center
rgb
center
rgb
area
hash
...
hash
radius
center
...
TColor
invert
red
...
© Oscar Nierstrasz
hash
TCircle ^ self radius hash bitXor:
self center hash
rgb
...
12.13
ST — Understanding Classes and Metaclasses
Composition Rules
1.
2.
Class methods take precedence over trait methods
Composition is commutative
— Conflict resolution is always explicit
3.
Flattening Property
— Trait methods have no special semantics
© Oscar Nierstrasz
12.14
ST — Understanding Classes and Metaclasses
Rule 2: Explicit Conflict Resolution
ColoredCircle
TCircle
hash
hash -> circleHash
...
TColor
hash -> colorHash
1)
...
Override the conflict with a glue method
— Aliases provide access to conflicting methods
2)
Exclude conflicting methods
© Oscar Nierstrasz
12.15
ST — Understanding Classes and Metaclasses
Composition Rules
1.
2.
Class methods take precedence over trait methods
Composition is commutative
— Conflict resolution is always explicit
3.
Flattening Property
— Trait methods have no special semantics
© Oscar Nierstrasz
12.16
ST — Understanding Classes and Metaclasses
Rule 3: Flattening Property
Visual
hash
Circle
radius
center
radius
center
TCircle
area
diameter
hash
© Oscar Nierstrasz
hash
^ super hash bitXor:
area
diameter
area
diameter
selfradius
radius*squared
hash
^ self radius *squared
2 ^ self
2
radius
center
...
12.17
ST — Understanding Classes and Metaclasses
Roadmap
>
>
>
>
>
>
>
Problems with Inheritance
Traits
Refactoring Collections with Traits
Traits in Squeak
Classboxes
Traits and Classboxes
Ongoing Research
© Oscar Nierstrasz
12.18
ST — Understanding Classes and Metaclasses
Problems with the Smalltalk
Collections Hierarchy
>
The ST collection hierarchy suffers from:
—
—
—
—
Duplicated code
Methods implemented too high in the hierarchy
Inappropriate inheritance
Incomplete protocols
© Oscar Nierstrasz
12.19
ST — Understanding Classes and Metaclasses
Methods implemented “too high”
Collection
addAll: aCollection
aCollection do: [:each |
self add: each].
add:
addAll:
remove:
removeAll:
SequenceableCollection
Set
Heap
add:
addAll:
remove:
removeAll:
add:
addAll:
remove:
removeAll:
© Oscar Nierstrasz
add: anObject
self shouldNotImplement
Array
remove: anObject
self shouldNotImplement
add:
remove:
12.20
ST — Understanding Classes and Metaclasses
Inappropriate Inheritance
Set
size
size
union:
union:
...
remove:
removeAll:
...
Dictionary
remove:
removeAll:
...
© Oscar Nierstrasz
Hard to see the real interface
of a class
> Unexpected runtime errors
>
remove: anObject
self shouldNotImplement
removeAll: anObject
self shouldNotImplement
12.21
ST — Understanding Classes and Metaclasses
Classifying the Collection Classes
>
Many different classification criteria
— Order
–
–
–
unordered (Set)
explicitly ordered (LinkedList)
implicitly ordered (Heap)
— Extensibility
–
–
fixed size (Array)
variable size (OrderedCollection)
— Mutability
–
–
immutable (String)
mutable (the others)
— Comparison
–
–
© Oscar Nierstrasz
using “identity” (IdentitySet)
using “equals” (Set)
12.22
ST — Understanding Classes and Metaclasses
Refactoring Strategy
Create traits for the identified properties
> Combine them to build the collection classes
>
Extensible
Functional
properties
Collection
ExplicitlyOrdered
ImplicitlyOrdered
Extensible
Implementation
properties
© Oscar Nierstrasz
ArrayBased
Linked
ExplicitlyOrdered
ArrayBased
12.23
Facilities supported by
all collection classes
Concrete classes adding
implementation traits
Common combinations
of functional traits
ST — Understanding Classes and Metaclasses
What Did We Gain?
>
Consistent hierarchies
— No inappropriate inheritance
— No methods implemented too high (before ~10%)
— Protocols are uniform and complete
>
Less code
— Refactored 38 classes with 1252 methods
— Created a total of 67 traits
— After the refactoring
~ 10% less source code
> 20% fewer methods
>
Improved Reusability
— “Toolbox of traits” makes it easy to build new classes
Black, et al., “Applying Traits to the Smalltalk Collection Hierarchy,” OOPSLA
2003
© Oscar Nierstrasz
12.25
ST — Understanding Classes and Metaclasses
Roadmap
>
>
>
>
>
>
>
Problems with Inheritance
Traits
Refactoring Collections with Traits
Traits in Squeak
Classboxes
Traits and Classboxes
Ongoing Research
© Oscar Nierstrasz
12.26
ST — Understanding Classes and Metaclasses
Traits in Squeak
>
Language Extension
— Extended the language kernel to represent traits
— Modified the compilation process for classes
built from traits
>
No changes to the Squeak VM
— Essentially no runtime performance penalty
— Except indirect instance variable access
— But: This is common practice anyway
No duplication of source code
> Small amount of byte-code duplication
>
— Only methods with super-sends
© Oscar Nierstrasz
12.27
ST — Understanding Classes and Metaclasses
Traits in Squeak 3.9
Object subclass: #Behavior
uses: TPureBehavior @
{ #basicAddTraitSelector:withMethod:
-> #addTraitSelector:withMethod: }
instanceVariableNames: 'superclass methodDict format
traitComposition localSelectors'
classVariableNames: 'ObsoleteSubclasses'
poolDictionaries: ''
category: 'Kernel-Classes'
© Oscar Nierstrasz
12.28
ST — Understanding Classes and Metaclasses
Practical Impact of Traits
>
Perl
— Traits were ported to Perl 5 (by Stevan Little)
— Traits are planned as a standard feature of Perl 6
>
VisualWorks Smalltalk
— Traits were ported to VW (by Terri Raymond)
>
Scala (developed at EPFL)
— Traits are a built-in language feature of Scala
— Fully integrated into the static type system
>
.NET
— Microsoft Research Project to bring traits to C#
© Oscar Nierstrasz
12.29
ST — Understanding Classes and Metaclasses
Roadmap
>
>
>
>
>
>
>
Problems with Inheritance
Traits
Refactoring Collections with Traits
Traits in Squeak
Classboxes
Traits and Classboxes
Ongoing Research
© Oscar Nierstrasz
12.30
ST — Understanding Classes and Metaclasses
Class Extension
>
A Class Extension is the ability to add or redefine
methods on a class after its creation
— Solves a different problem than subclassing
–
Clients of existing classes see the extensions
— Common in dynamic languages like CLOS and Smalltalk
© Oscar Nierstrasz
12.31
ST — Understanding Classes and Metaclasses
Visitor example
BlackPackage
BluePackage
Opr
acceptVisitor()
Add
Mult
acceptVisitor()
acceptVisitor()
© Oscar Nierstrasz
Visitor
doAdd()
doMult()
12.32
ST — Understanding Classes and Metaclasses
Subclassing does not Solve it
Opr
Add
Mult
Add’
Mult’
acceptVisitor()
acceptVisitor()
Parser
parse()
…
Add.new()
…
Subclasses are not referenced by the tree constructor
© Oscar Nierstrasz
12.33
ST — Understanding Classes and Metaclasses
In Smalltalk
>
Class extensions are global
— Any application can modify any class in the system
Consequences:
— Conflicts may arise
–
e.g., two applications may add the same method
— System fragility
–
e.g., an application may redefine a critical method
Problems:
— How to control class extensions?
— How to apply a set of unanticipated changes without breaking
existing clients?
© Oscar Nierstrasz
12.34
ST — Understanding Classes and Metaclasses
Classboxes
>
A Classbox
— Is a unit of scoping
–
I.e., a namespace
— Can define classes
— Can import class definitions from other classboxes
— Can define class extensions
–
>
I.e., methods on classes in scope
Definitions are local to the classbox that introduces them
— Changes only impact the classbox itself and classboxes that
explicitly import its definitions
© Oscar Nierstrasz
12.35
ST — Understanding Classes and Metaclasses
Classboxes: Avoiding Conflict
Since class extensions
local to a classbox,
conflicts are avoided
TextClassbox
import
String
URLClassbox
URL
WWWClassbox
String
asUrl
WWWURL
WWWURL.new()
…
© Oscar Nierstrasz
String
asUrl
URL.new()
…
12.36
ST — Understanding Classes and Metaclasses
Classboxes: Import and Visibility
Extensions can be imported
by other classboxes
TextClassbox
import
String
URLClassbox
URL
RedClassbox
…
url = “http://www.iam.unibe.ch/~scg”.asUrl()
© Oscar Nierstrasz
String
asUrl
12.37
ST — Understanding Classes and Metaclasses
Classbox as a Sandbox
A classbox establishes a purely
local scope for extensions, so
they cannot break applications
that do not import the extensions.
CollectionClassbox
import
OrderedCollection
do()
GreenClassbox
OrderedCollection
do()
aCollection.do(…)
C.new().foo()
© Oscar Nierstrasz
C
foo()
12.38
ST — Understanding Classes and Metaclasses
Local consistency
CollectionClassbox
Any expression executed in a
classbox will be evaluated from the OrderedCollection
perspective of that classbox alone.
do()
copy() 2
self.do(element.copy())
aCollection.copy(…)
C.new().bar()
© Oscar Nierstrasz
import
GreenClassbox
OrderedCollection
do() 3
C
bar() 1
12.39
ST — Understanding Classes and Metaclasses
From within the Green Classbox
self.do(element.copy())
aCollection.copy(…)
C.new().bar()
© Oscar Nierstrasz
GreenClassbox
OrderedCollection
do() 3
copy() 2
C
bar() 1
12.40
ST — Understanding Classes and Metaclasses
Implementation
>
Implemented in Squeak, an open-source Smalltalk
— New method lookup to take classboxes into account
–
–
–
Originating classbox
Collection of all the traversed classboxes
Import before inheritance
— Intensive use of reflection:
–
–
© Oscar Nierstrasz
Reification of the method calls stack
Message passing control
12.41
ST — Understanding Classes and Metaclasses
Roadmap
>
>
>
>
>
>
>
Problems with Inheritance
Traits
Refactoring Collections with Traits
Traits in Squeak
Classboxes
Traits and Classboxes
Ongoing Research
© Oscar Nierstrasz
12.42
ST — Understanding Classes and Metaclasses
Traits + Classboxes
>
Collaborating traits should be applied to a set of classes
— Use classboxes to encapsulate and apply
Bergel and Ducasse, “Supporting Unanticipated Changes with Traits and Classboxes,” NODE 2005
© Oscar Nierstrasz
12.43
ST — Understanding Classes and Metaclasses
Cross-Cutting Collaborations
>
Used to describe cross-cutting features by layering an
application into collaborations [Holland, ECOOP 92].
— A role is a set of features intended to be applied to a class.
— A collaboration is a set of roles intended to be applied to another
collaboration.
>
With Mixin-layers [Batory, ECOOP 98]:
— a role is a mixin
— a collaboration is a parametrized class
>
With Traits and Classboxes
— A role is encapsulated as a trait
— A collaboration is encapsulated as a classbox
© Oscar Nierstrasz
12.44
ST — Understanding Classes and Metaclasses
Example: Graph Application using
Inheritance
UndirectedGraph
Graph
Vertex
GraphCycle
VertexCycle
GraphRegions
VertexRegions
CycleChecking
Workspace
ConnectedRegion
WorkRegions
© Oscar Nierstrasz
12.45
ST — Understanding Classes and Metaclasses
The Graph Application using
Traits/Classboxes
UndirectedGraph
GraphTUGraph
VertexTVertexAdj
Graph
Vertex
Graph
Vertex
CycleChecking
Workspace
WNumber
GraphDFT
VertexDFT
ConnectedRegion
Workspace
WRegions
© Oscar Nierstrasz
GraRegions
VerRegions
12.46
ST — Understanding Classes and Metaclasses
Gain with Traits and Classboxes
>
No subclasses
— Identity of participant preserved.
>
A collaboration can be used to defined unanticipated
change
— Scope of change is limited to extending classbox and clients
>
Bounded visibility of extensions
— Multiple versions of classes can be simultaneously active in the
system
© Oscar Nierstrasz
12.47
ST — Understanding Classes and Metaclasses
Roadmap
>
>
>
>
>
>
>
Problems with Inheritance
Traits
Refactoring Collections with Traits
Traits in Squeak
Classboxes
Traits and Classboxes
Ongoing Research
© Oscar Nierstrasz
12.48
ST — Understanding Classes and Metaclasses
Ongoing research
>
Scoped reflection
— Restricting both availability and effect of reflection to given
scope
>
Changeboxes
— Encapsulating changes, not just extensions
— For both forward- and reverse-engineering
>
Context-oriented programming
— Software systems whose behaviour is context-dependent
© Oscar Nierstrasz
12.49
ST — Understanding Classes and Metaclasses
What you should know!
 Why does single inheritance lead to duplicated code?
 How does the composing class retain control of trait






composition?
What do “glue” methods do for traits?
What is the “flattening property” and why is it important
for traits?
Why is there “inappropriate inheritance” in the Smalltalk
Collections hierarchy?
What is a “class extension”?
In what way to classboxes ensure locality of changes?
What problems are solved by combined traits and
classboxes?
© Oscar Nierstrasz
12.50
ST — Understanding Classes and Metaclasses
Can you answer these questions?
 Why do multiple inheritance and mixins leads to “fragile
class hierarchies”?
 C++, Eiffel and Python all offer multiple inheritance – are
they broken?
 Why don’t traits specify any state?
 How much code is duplicated in the standard Java
libraries?
 What problems occur in Java due to the lack of class
extensions?
 Can classboxes be “flattened” in the same way that traits
can? Why or why not?
© Oscar Nierstrasz
12.51
ST — Understanding Classes and Metaclasses
License
>
http://creativecommons.org/licenses/by-sa/3.0/
Attribution-ShareAlike 3.0 Unported
You are free:
to Share — to copy, distribute and transmit the work
to Remix — to adapt the work
Under the following conditions:
Attribution. You must attribute the work in the manner specified by the author or licensor
(but not in any way that suggests that they endorse you or your use of the work).
Share Alike. If you alter, transform, or build upon this work, you may distribute the
resulting work only under the same, similar or a compatible license.
For any reuse or distribution, you must make clear to others the license terms of this work. The
best way to do this is with a link to this web page.
Any of the above conditions can be waived if you get permission from the copyright holder.
Nothing in this license impairs or restricts the author's moral rights.
© Oscar Nierstrasz
12.52