12. Traits and Classboxes (and Changeboxes). © Oscar Nierstrasz ST — Understanding Classes and Metaclasses 12.2 Roadmap  Problems with Inheritance 

Slides:



Advertisements
Similar presentations
Dynamic Object-Oriented Programming with Smalltalk 1. Introduction Prof. O. Nierstrasz.
Advertisements

Dynamic Object-Oriented Programming with Smalltalk 1. Introduction Prof. O. Nierstrasz.
8. Static Single Assignment Form Marcus Denker. © Marcus Denker SSA Roadmap  Static Single Assignment Form (SSA)  Converting to SSA Form  Examples.
Modeling Change as a First-Class Entity Oscar Nierstrasz Software Composition Group, University of Bern
ESE Einführung in Software Engineering 6. Modeling Objects and Classes Prof. O. Nierstrasz.
ESE Einführung in Software Engineering 7. Modeling Behaviour Prof. O. Nierstrasz.
Introduction to Software Engineering 7. Modeling Behaviour.
CSE 425: Semantics II Implementing Scopes A symbol table is in essence a dictionary –I.e., every name appears in it, with the info known about it –Usually.
OORPT Object-Oriented Reengineering Patterns and Techniques 7. Problem Detection Prof. O. Nierstrasz.
Interface & Abstract Class. Interface Definition All method in an interface are abstract methods. Methods are declared without the implementation part.
“Traits: Composable Units of Behavior” N. Schaerli, S. Ducasse, O. Nierstrasz, and A. Black, U Bern / OHSU, ECOOP 2003 “Traits: A Mechanism for Fine-grained.
12. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Roadmap  Summary: —Trends in programming paradigms  Research:...
7. Understanding Classes and Metaclasses. © Oscar Nierstrasz ST — Understanding Classes and Metaclasses 7.2 Roadmap  Metaclasses in 7 points  Indexed.
ESE Einführung in Software Engineering N. XXX Prof. O. Nierstrasz Fall Semester 2009.
© Oscar Nierstrasz ST — Smalltalk Basics 2.1 Change sets  Make sure your changes are logged to a new change set.
The Software Composition Group Prof. O. Nierstrasz
13. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Summary, Trends, Research...  Summary: functional, logic and object-oriented.
ESE Einführung in Software Engineering X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
13. A bit of Smalltalk. © Oscar Nierstrasz 2 Roadmap  The origins of Smalltalk  What is Smalltalk?  Syntax in a nutshell  Seaside — web development.
Dynamic Object-Oriented Programming with Smalltalk 1. Introduction Prof. O. Nierstrasz Summer Semester 2006.
13. Traits. Selected literature  Cook. Interfaces and Specifications for the Smalltalk-80 Collection Classes. OOPSLA 1992  Taivalsaari. On the Notion.
Metamodeling Seminar X. CHAPTER Prof. O. Nierstrasz Spring Semester 2008.
© Oscar Nierstrasz ST — Smalltalk Basics 2.1 Change sets  Make sure your changes are logged to a new change set.
ESE Einführung in Software Engineering X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
N. XXX Prof. O. Nierstrasz Thanks to Jens Palsberg and Tony Hosking for their kind permission to reuse and adapt the CS132 and CS502 lecture notes.
9. Understanding Classes and Metaclasses. Birds-eye view © Oscar Nierstrasz ST — Introduction 1.2 Reify your metamodel — A fully reflective system models.
7. Fixed Points. © O. Nierstrasz PS — Fixed Points 7.2 Roadmap  Representing Numbers  Recursion and the Fixed-Point Combinator  The typed lambda calculus.
12. Summary, Trends, Research. © O. Nierstrasz PS — Summary, Trends, Research Roadmap  Summary: —Trends in programming paradigms  Research:...
ESE Einführung in Software Engineering 6. Modeling Objects and Classes Prof. O. Nierstrasz.
Chapter 10 Classes Continued
12. Traits and Classboxes. © Oscar Nierstrasz ST — Traits and Classboxes 12.2 Roadmap  Problems with Inheritance  Traits  Refactoring Collections with.
OORPT Object-Oriented Reengineering Patterns and Techniques X. CHAPTER Prof. O. Nierstrasz.
CP — Concurrent Programming X. CHAPTER Prof. O. Nierstrasz Wintersemester 2005 / 2006.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
12. eToys. © O. Nierstrasz PS — eToys 12.2 Denotational Semantics Overview:  … References:  …
1 Advanced Abstraction Mechanisms  Mixins  Traits  Delegation.
Comparison of OO Programming Languages © Jason Voegele, 2003.
UFCEUS-20-2 : Web Programming Lecture 5 : Object Oriented PHP (1)
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
School of Computer Science & Information Technology G6DICP - Lecture 22 The Theory of Object Oriented Programming.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Copyright 2002 Prentice-Hall, Inc. Modern Systems Analysis and Design Third Edition Jeffrey A. Hoffer Joey F. George Joseph S. Valacich Chapter 20 Object-Oriented.
Database Management System Prepared by Dr. Ahmed El-Ragal Reviewed & Presented By Mr. Mahmoud Rafeek Alfarra College Of Science & Technology Khan younis.
Chapter 9 Object-Oriented Software Development F Software Development Process F Analyze Relationships Among Objects F Class Development F Class Design.
Instructor: Tasneem Darwish1 University of Palestine Faculty of Applied Engineering and Urban Planning Software Engineering Department Object Oriented.
Chapter 12 Support for Object oriented Programming.
Objects & Dynamic Dispatch CSE 413 Autumn Plan We’ve learned a great deal about functional and object-oriented programming Now,  Look at semantics.
S.Ducasse Stéphane Ducasse savoie.fr e/ e/ 1 Inheritance Semantics and Method Lookup.
Object Oriented Software Development
E.Bertino, L.Matino Object-Oriented Database Systems 1 Chapter 5. Evolution Seoul National University Department of Computer Engineering OOPSLA Lab.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
(1) ICS 313: Programming Language Theory Chapter 12: Object Oriented Programming.
OOPs Object oriented programming. Abstract data types  Representationof type and operations in a single unit  Available for other units to create variables.
Object Oriented Programming
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Session 6 Comments on Lab 3 & Implications of Inheritance.
Data Design and Implementation. Definitions Atomic or primitive type A data type whose elements are single, non-decomposable data items Composite type.
Fusion Design Overview Object Interaction Graph Visibility Graph Class Descriptions Inheritance Graphs Fusion: Design The overall goal of Design is to.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
A Survey of Object-Oriented Concept Oscar Nierstrasz.
Traits by Nathanael Sch ä rli, St é phane Ducasse, Oscar Nierstrasz and Andrew P. Black.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
1 Case Study: Meta Classes  Class representation in memory  Class variables and class methods  Meta Classes  3 Level System  4 Level System  5 Level.
CSE 413 Programming Languages & Implementation Hal Perkins Autumn 2012 Multiple Inheritance, Interfaces, Mixins 1.
Lec 3: Object-Oriented Data Modeling
Chapter 20 Object-Oriented Analysis and Design
More Object-Oriented Programming
Presentation transcript:

12. Traits and Classboxes (and Changeboxes)

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses 12.2 Roadmap  Problems with Inheritance  Traits  Refactoring Collections with Traits  Traits in Squeak  Classboxes  Traits and Classboxes  Ongoing Research Selected material courtesy of Nathanael Schaerli and Alexandre Bergel

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses 12.3 Roadmap  Problems with Inheritance  Traits  Refactoring Collections with Traits  Traits in Squeak  Classboxes  Traits and Classboxes  Ongoing Research

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses 12.4 How Can We Implement This? Circle Visual BorderedCircleBorderedRectangle Rectangle Bordered CircleRectangle Bordered

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses 12.5 Alternative Approaches  Single inheritance leads to code duplication  Alternatives: —Multiple inheritance —Mixins

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses 12.6 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 ST — Understanding Classes and Metaclasses 12.7 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 ST — Understanding Classes and Metaclasses 12.8 Roadmap  Problems with Inheritance  Traits  Refactoring Collections with Traits  Traits in Squeak  Classboxes  Traits and Classboxes  Ongoing Research

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses 12.9 Traits Circle Rectangle Polygon Colored Bordered Traits = Building Blocks Circle RectanglePolygon CircleColoredBordered RectangleColored + + +

© Oscar Nierstrasz 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 radius radius: center center:

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses Using Traits to Compose Classes ColoredCircle Visual TCircle TColor Class = Superclass + State + Traits + Glue methods Class = Class = Superclass Class = Superclass + State Class = Superclass + State + Traits rgbradiuscenter The composing class retains control of the composition.

© Oscar Nierstrasz 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 ST — Understanding Classes and Metaclasses Rule 1: Precedence of Class Methods ColoredCircle TCircle area hash... radius center... TColor invert red... rgb... rgbradiuscenter radius center... rgb... area hash... radius center... rgb... area hash... radius center rgb hash ^ self radius hash bitXor: self center hash

© Oscar Nierstrasz 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 ST — Understanding Classes and Metaclasses Rule 2: Explicit Conflict Resolution ColoredCircle TCircle hash... TColor hash... 1) Override the conflict with a glue method —Aliases provide access to conflicting methods 2) Exclude conflicting methods hash hash -> circleHash hash -> colorHash

© Oscar Nierstrasz 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 ST — Understanding Classes and Metaclasses Rule 3: Flattening Property Circle radius center TCircle radius center... radiuscenter Visual hash area ^ self radius squared area diameter hash ^ super hash bitXor: self radius hash diameter ^ self radius * 2 area ^ self radius squared diameter ^ self radius * 2

© Oscar Nierstrasz 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 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 ST — Understanding Classes and Metaclasses Methods implemented “too high” Collection Sequenceable- Collection Array HeapSet add: addAll: remove: removeAll: add: addAll: remove: removeAll: add: addAll: remove: removeAll: add: remove: Array add: anObject self shouldNotImplement remove: anObject self shouldNotImplement add: addAll: remove: removeAll: addAll: aCollection aCollection do: [:each | self add: each].

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses Inappropriate Inheritance Set size union: remove: removeAll:... Dictionary remove: removeAll:... size union:... remove: anObject self shouldNotImplement removeAll: anObject self shouldNotImplement size union: remove: removeAll:...  Hard to see the real interface of a class  Unexpected runtime errors

© Oscar Nierstrasz 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 – using “identity” ( IdentitySet ) – using “equals” ( Set )

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses ImplicitlyOrdered Linked Extensible ExplicitlyOrdered ArrayBased Refactoring Strategy  Create traits for the identified properties  Combine them to build the collection classes Extensible ExplicitlyOrdered ArrayBased Collection Functional properties Implementation properties Extensible ExplicitlyOrdered ArrayBased

Facilities supported by all collection classes Concrete classes adding implementation traits Common combinations of functional traits

© Oscar Nierstrasz 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 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 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 ST — Understanding Classes and Metaclasses Traits in Squeak 3.9 Object subclass: #Behavior uses: { #basicAddTraitSelector:withMethod: -> #addTraitSelector:withMethod: } instanceVariableNames: 'superclass methodDict format traitComposition localSelectors' classVariableNames: 'ObsoleteSubclasses' poolDictionaries: '' category: 'Kernel-Classes'

© Oscar Nierstrasz 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 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 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 ST — Understanding Classes and Metaclasses Visitor example BlackPackage Opr AddMult acceptVisitor() BluePackage Visitor doAdd() doMult()

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses Subclassing does not Solve it Opr Add Mult Parser parse() Add.new() … … Subclasses are not referenced by the tree constructor Add’Mult’ acceptVisitor()

© Oscar Nierstrasz 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 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 ST — Understanding Classes and Metaclasses Classboxes: Avoiding Conflict Since class extensions local to a classbox, conflicts are avoided TextClassbox String import WWWClassbox WWWURL String asUrl WWWURL.new() … URLClassbox URL String asUrl URL.new() …

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses Classboxes: Import and Visibility Extensions can be imported by other classboxes TextClassbox String import URLClassbox URL String asUrl RedClassbox … url = “

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses Classbox as a Sandbox CollectionClassbox OrderedCollection import do() A classbox establishes a purely local scope for extensions, so they cannot break applications that do not import the extensions. C foo() aCollection.do(…) C.new().foo() GreenClassbox OrderedCollection do()

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses Local consistency Any expression executed in a classbox will be evaluated from the perspective of that classbox alone. CollectionClassbox OrderedCollection import do() copy() OrderedCollection do() C 3 1 aCollection.copy(…) bar() GreenClassbox 2 self.do(element.copy()) C.new().bar()

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses From within the Green Classbox aCollection.copy(…) C.new().bar() self.do(element.copy()) OrderedCollection do() C 1 3 bar() GreenClassbox 2 copy()

© Oscar Nierstrasz 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: – Reification of the method calls stack – Message passing control

© Oscar Nierstrasz 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 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 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 ST — Understanding Classes and Metaclasses Example: Graph Application using Inheritance UndirectedGraph GraphVertex CycleChecking GraphCycleVertexCycleWorkspace ConnectedRegion GraphRegionsVertexRegionsWorkRegions

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses UndirectedGraph GraphVertex TUGraph TVertexAdj The Graph Application using Traits/Classboxes CycleChecking GraphVertex Workspace GraphDFT VertexDFT WNumber ConnectedRegion GraphVertexWorkspace WRegionsGraRegionsVerRegions

© Oscar Nierstrasz 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 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 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 ST — Understanding Classes and Metaclasses Changeboxes  Encapsulate change —Capture changes to methods, state, class hierarchy – Express semantics of refactoring and other changes  Delimit the scope of change —Restrict scope of changes to specific clients – Delay global impact  Enable changes depending on context —Dynamically extend the scope of changes – Manage system evolution  Dispatch on dynamic context —Dynamically apply or disable changes – Temporally or contextually scope changes

© Oscar Nierstrasz ST — Understanding Classes and Metaclasses 12.51

© Oscar Nierstrasz 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 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 ST — Understanding Classes and Metaclasses 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. License 