Programming in Scala Mixin inheritance Summer 2008

Similar documents
CS Programming Languages: Scala

Imperative Programming 2: Traits

G Programming Languages - Fall 2012

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

Programming in Scala Second Edition

Java Object Oriented Design. CSC207 Fall 2014

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Polymorphism. return a.doublevalue() + b.doublevalue();

Distributed Systems Recitation 1. Tamim Jabban

Exercise 8 Parametric polymorphism November 18, 2016

Distributed Systems Recitation 1. Tamim Jabban

Software Engineering Design & Construction

CISC 3115 Modern Programming Techniques Spring 2018 Section TY3 Exam 2 Solutions

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

ITI Introduction to Computing II

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Week 3: Functions and Data. Working with objects. Members of an object. = n 1d 2 n 2 d 1. + n 2. = n 1d 2. = n 1n 2 / n 2. = n 2

Week 3: Functions and Data

ITI Introduction to Computing II

Inheritance. Transitivity

Scala. Fernando Medeiros Tomás Paim

15 Multiple Inheritance and Traits

Exercise 6 Multiple Inheritance, Multiple Dispatch and Linearization November 4, 2016

Big Java Late Objects

Making New instances of Classes

CS-202 Introduction to Object Oriented Programming

Object-oriented programming

About This Lecture. Data Abstraction - Interfaces and Implementations. Outline. Object Concepts. Object Class, Protocol and State.

Introduction to Scala

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Computer Science 210: Data Structures

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Chapter 5: Procedural abstraction. Function procedures. Function procedures. Proper procedures and function procedures

Scala. The scalabale Language. May 30, Department of Computer Sciences University of Salzburg. Functional Features Object oriented Features

CMPSCI 187: Programming With Data Structures. Lecture 6: The StringLog ADT David Mix Barrington 17 September 2012

8.1 Inheritance. 8.1 Class Diagram for Words. 8.1 Words.java. 8.1 Book.java 1/24/14

Programming II (CS300)

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

JAVA MOCK TEST JAVA MOCK TEST II

C12a: The Object Superclass and Selected Methods

Inheritance & Polymorphism

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Software Engineering: Design & Construction

Java Programming Training for Experienced Programmers (5 Days)

Exercise 6 Multiple Inheritance, Multiple Dispatch and Linearization November 3, 2017

Software Engineering Design & Construction

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Programming Exercise 14: Inheritance and Polymorphism

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

An Introduction to Scala for Spark programming

Programming II (CS300)

Object-Oriented Concepts and Design Principles

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

Chapter 13 Abstract Classes and Interfaces

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Everything is an object. Almost, but all objects are of type Object!

abstract classes & types

Programming Paradigms

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Chapter 5 Object-Oriented Programming

PROGRAMMING LANGUAGE 2

CPS 506 Comparative Programming Languages. Programming Language

Foundations of object orientation

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

UI Software Organization

University of Tartu Faculty of Mathematics and Computer Science Institute of Computer Science

Chapter 6 Introduction to Defining Classes

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

WA1278 Introduction to Java Using Eclipse

Data Structures and Algorithms Design Goals Implementation Goals Design Principles Design Techniques. Version 03.s 2-1

CS1004: Intro to CS in Java, Spring 2005

More On inheritance. What you can do in subclass regarding methods:

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

The class Object. Lecture CS1122 Summer 2008

Super-Classes and sub-classes

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

Inheritance. Inheritance

Software Engineering Design & Construction

TeenCoder : Java Programming (ISBN )

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Java Review. Fundamentals of Computer Science

Building Java Programs

Data Structures (list, dictionary, tuples, sets, strings)

Understanding Inheritance and Interfaces

Java Fundamentals (II)

Java Classes, Inheritance, and Interfaces

CS506 Web Design & Development Final Term Solved MCQs with Reference

Chapter 13 Abstract Classes and Interfaces

Introduction to Programming Using Java (98-388)

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

COMP 401: THE DUAL ROLE OF A CLASS. Instructor: Prasun Dewan (FB 150,

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview. Elements of Programming Languages. Objects. Self-Reference

Java classes cannot extend multiple superclasses (unlike Python) but classes can implement multiple interfaces.

More about inheritance

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Reviewing OO Concepts

Transcription:

Programming in Scala Mixin inheritance Summer 2008 1

The very short history of multiple inheritance C++ had multiple inheritance Java removed it Mostly due to diamondinheritance problem. Should alice behave like Women are defined to behave, or like Directors are defined to behave? Person Woman Director «instanceof» «instanceof» alice 2

Mixin-based inheritance Scala allows mixin-type inheritance to be used as a mean to improve reusability and modularization Contents of this talk: 1. Introduction 2. Sparse interfaces versus rich interfaces 3. Stackable modifications via traits 4. Improving modularization of JSF beans Themes 1-3 are rephrased from the chapter 12 of Programming in Scala 3

Theme 1: Introduction Inheritance between two classes can be defined as R = P ΔR where R is the newly defined subclass, P denotes the properties inherited from an existing class, ΔR denotes the incrementally added new properties that differentate R from P and stands for operation of combining P and ΔR 4

Traditional (single-)inheritance Traditional inheritance defines classes as Class P is [..properties..] Endclass Class R inherits P and [.. modifies P by ΔR.. ] Endclass 5

Mixin-inheritance In mixin-inheritance, the ΔR part is written into its own mixin-class, as: Class P is [ properties ] Endclass Class R mixin is [ modifications (ΔR) ] Endclass Class R inherits P, R mixin. 6

Properties of mixins One never instantiates a mixin; but a mixin is combined with a concrete class Many mixins can be combined with a concrete class at a time The order of the mixins gives a resolution to the diamond-inheritance problem Both abstract methods and concrete methods can be contained in a mixin-class This is different than in Java, which allows multiple inheritance via interfaces only 7

Scala-examples Defining a mixin-class Philosophical: trait Philosophical { def philosophize() { println("i consume memory, therefore I am! ) The trait does not declare a superclass, so similar to classes, it has the default superclass of AnyRef. It defines one method, named philosophize, which is concrete. 8

Defining a philosophical frog abstract class Animal { def color: String override def tostring = a + color + animal. class Frog extends Animal with Philosophical { def color = "green" We ve defined three methods for class Frog: color(), tostring() and philosophize() 9

Traits are more than interfaces with implementations Traits do about all the same than classes, e.g. Traits can declare fields and contain state Traits can be defined in inheritance hierarchies Traits can be declared abstract There are two cases in which trait classes differ from regular classes: 1.It is not possible to define class parameters for traits it is the class, which defines how it is constructed 2.The super -calls are dynamically bound when the trait is mixed with a class 10

Theme 2: Sparse and Rich interfaces Sparse interfaces define just a few functions, which need to be implemented in the implementing class A tradeoff between caller convenience and implementor convenience In a rich interface, it is more work to implement all of the required methods The Java API favours sparse interfaces, due to single-inheritance Traits allow to reduce the tradeoff s effect 11

Example: a rectangle Rectangles are used in graphical user interfaces in various contexts: Windows have a rectangular bounding box Bitmap images are rectangular Regions selected with a mouse are rectangular We could implement the rectangulariness in the base class of all rectangular things But then, other aspects of these things would be missing A.k.a tyranny of dominant decomposition 12

An enrichment trait - Rectangular class Point trait Rectangular { def topleft: Point def bottomright: Point def left = topleft.x def right = bottomright.x def width = right - left def height = bottomright.y topleft.y; // and many more geometric methods... 13

A selection event (hypothetical) class SelectionEvent(val topleft: Point, val bottomright: Point) extends MouseEvent with Rectangular { // structure from MouseEvent is // mixed with Rectangular s methods and // attributes 14

A bitmap image (hypothetical) class Bitmap(val topleft: Point, val bottomright: Point) extends Rectangular { // It is also possible to directly to extend a trait class def setimage(img: Array[int]) = { if(img.length!= width * length) { throw new IllegalArgumentException(!! ); 15

Another trait-example: rational numbers class Rational(val numerator: Int, val denominator: Int) { //... def < (that: Rational) = this.numerator * that.denominator > that.numerator * this.denominator def > (that: Rational) = that < this def <= (that: Rational) = (this < that) (this == that) def >= (that: Rational) = (this > that) (this == that) 16

The ordered trait Rational s rich interface is cumbersome to write, as it would be duplicated in similar classes While the order can be defined with a single function, compare, it is inconvenient to need to write object1 compare object2 <= 0 when actually meaning to say object1 <= object2. Ordering of objects is another area where rich interfaces can be useful 17

Ordered.scala trait Ordered[A] { def compare(that: A): Int def < (that: A): Boolean = (this compare that) < 0 def > (that: A): Boolean = (this compare that) > 0 def <= (that: A): Boolean = (this compare that) <= 0 def >= (that: A): Boolean = (this compare that) >= 0 def compareto(that: A): Int = compare(that) 18

MixinRational.scala class MixinRational(val numer: Int, val denom: Int) extends Ordered[MixinRational] { //... def compare(that: MixinRational) = (this.numer * that.denom) - (that.numer * this.denom) // todo: define equals, hashcode 19

Theme 3: Stackable modifications Due to a trait s super-calls being bound dynamically, multiple traits can be stacked Let s think about a Queue, where you can put values into and get values from: abstract class IntQueue { def get(): Int def put(x: Int) 20

BasicIntQueue.scala import scala.collection.mutable.arraybuffer class BasicIntQueue extends IntQueue { private val buf = new ArrayBuffer[Int] def get() = buf.remove(0) def put(x: Int) { buf += x 21

Defining three behaviour modifying traits 1. Doubling: double all integers that are put in the queue 2. Incrementing: increment all integers that are put in the queue 3. Filtering: filter out negative integers from a queue 22

Doubling.scala trait Doubling extends IntQueue { abstract override def put(x: Int) { super.put(2 * x) abstract override is not possible for regular classes For traits, it means that this trait can only be mixed in with a class that already has the corresponding method concretely defined Usage: class MyQueue extends BasicIntQueue with Doubling 23

Incrementing.scala, Filtering.scala trait Incrementing extends IntQueue { abstract override def put(x: Int) { super.put(x + 1) trait Filtering extends IntQueue { abstract override def put(x: Int) { if (x >= 0) super.put(x) 24

Ordering of mixins is significant Basically, the list of mixin-modifications is traversed from right to left Each new mixin is put on stack of the previous ones new BasicIntQueue with Incrementing with Doubling First double, then increment new BasicInQueue with Doubling with Incrementing First increment, then double 25

Theme 4: JSF-example Java Server Faces, JSF, is a JSR-127, thus a standard way of constructing web applications in Java Facelets are a common technique for defining reuseable layouts in XML User interface state is contained in Managed beans, whose getters and setters follow the JavaBeans conventions 26

JSF data table Two components: a data table and a scroller Data table s state List of cars First row number Scroller s state Number of pages Current page 27

Car listing s backing bean A managed bean in Java, which contains accessors for both the data table and the scroller s state class CarListingManagedBean { private int startingrow; private Object carlisting; // an array or an iterator private int currentpage; private int pagecount; public void setstartingrow(int i) { public int getstartingrow() {... 28

Single-point of non-modularization While the facelet UI pages can be modularized to a reasonable degree, the managed bean part tends to become a mold of all corresponding state variables E.g. both the data table s and scroller s variables are contained in the one UI bean class When reusing the same UI components, the state variables and accessors are duplicated to multiple managed beans 29

Traits to the rescue With traits, we can isolate each of the UI component s state variables into their own modules For a given UI page s backing bean, mix in the corresponding traits E.g. trait DataScrollerBacker { var currentpage: int; var lastpage: int; trait DataTableBacker { var startingrow: int; var listing: Object; 30

References [Bracha & Cook 1990]: Mixin-based inheritance [Taivalsaari 1996]: On the notion of inheritance 31