“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.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Understand and appreciate Object Oriented Programming (OOP) Objects are self-contained modules or subroutines that contain data as well as the functions.
Object Oriented Programming Chapter 7 Programming Languages by Ravi Sethi.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
Stéphane Ducasse«ChapterNr».1 Selected Design Patterns Design Patterns are recurrent solutions to design problems They are pros and cons We already saw:
Interface & Abstract Class. Interface Definition All method in an interface are abstract methods. Methods are declared without the implementation part.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
Object-Oriented PHP (1)
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
12. Traits and Classboxes (and Changeboxes). © Oscar Nierstrasz ST — Understanding Classes and Metaclasses 12.2 Roadmap  Problems with Inheritance 
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 10 Classes Continued
12. Traits and Classboxes. © Oscar Nierstrasz ST — Traits and Classboxes 12.2 Roadmap  Problems with Inheritance  Traits  Refactoring Collections with.
1 Advanced Abstraction Mechanisms  Mixins  Traits  Delegation.
Object-oriented design CS 345 September 20,2002. Unavoidable Complexity Many software systems are very complex: –Many developers –Ongoing lifespan –Large.
Inheritance using Java
UFCEUS-20-2 : Web Programming Lecture 5 : Object Oriented PHP (1)
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
Lecture 3 Casting Abstract Classes and Methods Interfaces.
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Chapter 11 Inheritance and Composition. Chapter Objectives Learn about inheritance Learn about subclasses and superclasses Explore how to override the.
The Procedure Abstraction, Part VI: Inheritance in OOLs Comp 412 Copyright 2010, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled.
1 Computer Science 340 Software Design & Testing Inheritance.
CS212: Object Oriented Analysis and Design Lecture 13: Relationship between Classes.
Objects & Dynamic Dispatch CSE 413 Autumn Plan We’ve learned a great deal about functional and object-oriented programming Now,  Look at semantics.
Peyman Dodangeh Sharif University of Technology Fall 2014.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall
(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.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
Classes, Interfaces and Packages
Variations on Inheritance Object-Oriented Programming Spring
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Testing in OO Environment The reasons for testing is not any different for any of the design and implementation methodologies, including OO methodology.
Traits by Nathanael Sch ä rli, St é phane Ducasse, Oscar Nierstrasz and Andrew P. Black.
 The word static is used to declare either a ________ variable or method.  Why do we use statics?  What is Polymorphism? class In general, we use a.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Advanced Programming in Java
Modern Programming Tools And Techniques-I
Sections Inheritance and Abstract Classes
Name Spaces: ALL versus OOL
7.1 What Is An Object Object-oriented program - Description or simulation of application Object-oriented programming is done by adopting or extending an.
Chapter 11 Object-Oriented Design
Week 4 Object-Oriented Programming (1): Inheritance
Section 11.1 Class Variables and Methods
MSIS 670 Object-Oriented Software Engineering
Week 6 Object-Oriented Programming (2): Polymorphism
Advanced Programming Behnam Hatami Fall 2017.
Inheritance and Polymorphism
Object-Oriented PHP (1)
Final and Abstract Classes
Lecture 10 Concepts of Programming Languages
Presentation transcript:

“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 Reuse” S. Ducasse, O. Nierstrasz, N. Schaerli, R. Wuyts, and A. Black, ACM TOPLAS (forthcoming) Presented by Evgeniy Gabrilovich Traits Traits are primitive units of code reuse that consist only of methods (i.e., no state)

The quest for better reuse mechanisms Common forms of inheritance –Single / multiple / mixin inheritance Limitations of the different forms of inheritance Traits, traits, traits … –Introduction to traits –Usage examples –Discussion of trait properties –Implementation Smalltalk-80, Scala, C#/Rotor, Perl 6 (“roles”)

Key observation about reuse A class is not necessarily an appropriate element of reuse Two contradictory roles of classes –Generator of instances  A class must be complete  Each class should have a unique place in the class hierarchy –Unit of reuse  A class should be small  Units of reuse should be applicable at numerous arbitrary places

Single inheritance Not expressive enough for factoring out common features shared by classes in a complex hierarchy –Code duplication Smalltalk example ReadStreamWriteStream ReadWriteStream ? ReadStreamWriteStream ReadWriteStream Code duplication PositionableStream read + write functions

“Multiple inheritance is good, but there is no good way to do it” (Steve Cook, OOPSLA’87) Problem #1: Conflicting features that are inherited along different paths –Conflicting methods Can be resolved by overriding –Conflicting state variables A B D C

Problem #2: Limited compositional power A read write: B read write: A read write: SyncA read write: acquireLock releaseLock read self acquireLock res := super read self releaseLock ^ res write: val self acquireLock super write: val self releaseLock SyncReadWrite read write: acquireLock releaseLock SyncASyncB 

Multiple inheritance example in C++: base class with abstract methods class SyncReadWrite { public: virtual int read() { acquireLock(); result = directRead(); releaseLock(); return result; } virtual void write(int n) { acquireLock(); directWrite(n); releaseLock(); } protected: virtual void acquireLock() { // acquire lock } virtual void releaseLock() { // release lock } virtual int directRead() = 0; virtual void directWrite(int n) = 0; }; // end of class SyncReadWrite

Multiple inheritance example in C++: code duplication in child classes class SyncA : public A, SyncReadWrite { public: virtual int read() { return SyncReadWrite::read(); } virtual void write(int n) { SyncReadWrite::write(n); } protected: virtual int directRead() { return A::read(); } virtual void directWrite(int n) { A::write(n); } }; // end of class SyncA class SyncB : public B, SyncReadWrite { public: virtual int read() { return SyncReadWrite::read(); } virtual void write(int n) { SyncReadWrite::write(n); } protected: virtual int directRead() { return B::read(); } virtual void directWrite(int n) { B::write(n); } }; // end of class SyncB Code duplication

Let’s mix it! A mixin is an (abstract subclass) specification –may be applied to various classes to extend them with the same set of features Key idea: create components designed for reuse rather than for instantiation Implementation –C++ – using templates –Java – using (multiple inheritance of) interfaces –Smalltalk – language extension using a mixin invocation operator

Mixin example Rectangle asString ^ super asString, ‘ ‘, self color asString Rectangle + MColor asString serializeOn: MColor asString serializeOn: Rectangle + MColor + MBorder asString serializeOn: MyRectangle asString ^ super asString, ‘ ‘, self borderWidth asString MBorder asString serializeOn:

Mixins are not a panacea Problems? You bet! –It is impossible to control how individual features are composed –Composition of mixins is messy Mixins applied later in the chain (silently) override identically named features of earlier mixins Reestablishing the original behavior requires changes in other mixins –Modifying a mixin used in several places in a class hierarchy may be particularly unpleasant

Mixins in C++: no multiple inheritance template class MSyncReadWrite : public Super { public: virtual int read() { acquireLock(); result = Super::read(); releaseLock(); return result; } virtual void write(int n) { acquireLock(); Super::write(n); releaseLock(); } protected: virtual void acquireLock() { // acquire lock } virtual void releaseLock() { // release lock } }; // end of MSyncReadWrite class SyncA : public MSyncReadWrite {}; class SyncB : public MSyncReadWrite {};

Introduction to traits Lightweight software components –Basic building blocks for classes –Primitive units of code reuse A trait provides methods that implement behavior A trait requires methods that parameterize the provided behavior (optional) –Required methods are used by – not implemented in – a trait

Sample traits TCircle = hash < <= … area bounds circumference scaleBy: … center center: radius radius: TDrawing draw refresh refreshOn: bounds drawOn: Geometry-related behaviorDrawing-related behavior

Sample trait implementation in (an extension of) Smalltalk Trait named: #TDrawing uses: {} draw ^ self drawOn: World canvas refresh ^ self refreshOn: World canvas refreshOn: … bounds self requirement drawOn: aCanvas self requirement

Trait composition Classes are composed from traits –Provide required methods –Resolved conflicts due to trait composition Traits can be nested –The semantics for the containing class is not nested –Traits are inlined Nested traits are equivalent to flattened traits

Addressing known problems Traits specify no state –Methods provided by traits never access state variable directly Only using required methods –Can only cause method conflicts Can be resolved by overriding or by exclusion Traits are detached from the inheritance hierarchy Traits are not composed in any particular order

Class = Superclass + State + Traits + Glue methods TCircle = hash < <= … area bounds circumference scaleBy: … center center: radius radius: TDrawing draw refresh refreshOn: bounds drawOn: Circle initialize drawOn: center center: radius radius:

Sample class using traits Object subclass: #Circle instanceVariableNames: ‘center radius’ traits: {TCircle. TDrawing} initialize center := radius := 50 center ^ center radius ^ radius drawOn: aCanvas … center: aPoint center := aPoint radius: aNumber radius := aNumber

Completing a class definition In order for a class to be complete, all the requirements of the traits must be satisfied These methods can be implemented –in the class itself, –in a direct or indirect superclass, –by another trait that is used by the class.

The flattening property The semantics of a method defined in a trait is identical to the semantics of the same method defined in a class that uses the trait. –The keyword super has no special semantics for traits –super simply refers to the superclass of the class that uses the trait.

Nested traits TCircle < = hash TGeometry area bounds scaleBy: … center center: radius radius: TMagnitude <= > between:and: < TEquality ~== hash

Flattened nested traits TCircle < = hash area bounds scaleBy: … center center: radius radius: <= > between:and: ~=

More nested traits TEquality ~== hash TColor red green saturation red: … = hash rgb rgb:

Lack of composition order The order of trait composition is irrelevant  Conflicting trait methods must be explicitly disambiguated Precedence rules for conflict resolution –Class methods take precedence over trait methods (= overriding trait methods) –Traits methods take precedence over superclass methods (flattening property!)

Method conflicts TCircle = hash ~= … area bounds circumference scaleBy: … center center: radius radius: TDrawing draw refresh refreshOn: bounds drawOn: Circle initialize = hash rgb rgb: drawOn: center center: radius radius: TColor = hash ~= red … rgb rgb: TEquality ~== hash

traits: { { #circleHash -> #hash. #circleEqual: -> #= } } Conflict resolution Conflicts must be explicitly resolved –Conflicting methods are excluded, and turned into required ones Possible ways to resolve a conflict: –Define an overriding method in the class or in the composite trait –Rename conflicting methods (aliasing) –Avoid a conflict by explicitly excluding some methods traits: { TCircle. TDrawing. TColor - { #=. #hash. #~=. } }

C++ Revisited Document MSyncReadWrite > MLogOpenClose MyDocument Document TLogOpenClose MyDocument TSyncReadWrite virtual

Traits in C++ template class TLogOpenClose : virtual public Super { public: virtual void open() { … } virtual void close() { … } virtual void reset() { … } protected: virtual void log(const char* s) { … } }; // end of TLogOpenClose template class TSyncReadWrite : virtual public Super { public: virtual void read() { … } virtual void write(int n) { … } virtual void reset() { … } protected: virtual void acquireLock() { … } virtual void releaseLock() { … } }; // end of TSyncReadWrite class MyDocument : public TLogOpenClose, public TSyncReadWrite { … // glue code };

Traits in C++: what we can and cannot do Nested traits template class TLogAndSync : virtual public TLogOpenClose, virtual public TSyncReadWrite { }; Composition of traits –Sum … OK –Aliasing … can be simulated using scope operator :: –Exclusion … nope  Every conflict must be resolved by overriding the conflicting methods

Review of trait properties Untangling reusability and classes –Classes are instance generators and hence have to be complete –Units of reuse should be small Trait composition operates at a finer granularity than inheritance –Single inheritance is retained –Flattening property Conflicting features –Methods only, no state –If the same method from the same trait is obtained via multiple paths, there is no conflict

Evaluation against identified problems: code duplication Stream position position: WriteStream nextPut: position: ReadStream next ReadWriteStream next Code duplication

Stream hierarchy refactored using traits Stream position position: WriteStreamReadStream ReadWriteStream TReadStream TWriteStream

Evaluation against identified problems: duplicated wrappers Like mixins, traits can explicitly refer to a method implemented by the superclass B read write: A read write: SyncReadWrite read write: acquireLock releaseLock SyncASyncB  TSyncReadWrite read write: acquireLock releaseLock read write: A read write: SyncA

Mixin example (revisited) Rectangle asString ^ super asString, ‘ ‘, self color asString Rectangle + MColor asString serializeOn: MColor asString serializeOn: Rectangle + MColor + MBorder asString serializeOn: MyRectangle asString ^ super asString, ‘ ‘, self borderWidth asString MBorder asString serializeOn:

Evaluation against identified problems: composition Total ordering –Trait composition does not impose total ordering Dispersal of glue code –Glue code is always located in the combining entity The superordinate entity is in complete charge of plugging together the components that implement its features –Glue code is separated from the implementation of features

Traits offer more control Rectangle asString MyRectangle TColor asString serializeOn: TBorder asString serializeOn: Glue code

Evaluation against identified problems: fragile hierarchies Every method conflict must be resolved explicitly –This requires extra work … but you always get what you expect Changes mandated by conflict resolution are limited to the direct users of the trait –A direct client can simply exclude a new trait method Not so with mixins –introducing a new method may require changes to many other components or addition of new components