howto distinguish composition and self-typing use-cases
Asked Answered
D

1

11

Scala has two instruments for expressing object composition: original self-type concept and well known trivial composition. I'm curios what situations I should use which in.

There are obvious differences in their applicability. Self-type requires you to use traits. Object composition allows you to change extensions on run-time with var declaration.

Leaving technical details behind I can figure two indicators to help with classification of use cases. If some object used as combinator for a complex structure such as tree or just have several similar typed parts (1 car to 4 wheels relation) than it should use composition. There is extreme opposite use case. Lets assume one trait become too big to clearly observe it and it got split. It is quite natural that you should use self-types for this case.

That rules are not absolute. You may do extra work to convert code between this techniques. e.g. you may replace 4 wheels composition with self-typing over Product4. You may use Cake[T <: MyType] {part : MyType} instead of Cake { this : MyType => } for cake pattern dependencies. But both cases seem counterintuitive and give you extra work.

There are plenty of boundary use cases although. One-to-one relations is very hard to decide with. Is there any simple rule to decide what kind of technique is preferable?

self-type makes you classes abstract, composition makes your code verbose. self-type gives your problems with blending namespaces and also gives you extra typing for free (you got not just a cocktail of two elements but gasoline-motor oil cocktail known as a petrol bomb).

How can I choose between them? What hints are there?

Update:

Let us discuss the following example:

Adapter pattern. What benefits it has with both selt-typing and composition approaches?

Dichromaticism answered 16/6, 2012 at 1:39 Comment(5)
It looks like you've covered most of the trade-offs. I would add that composition is likely to be more familiar for less-skilled teams. You can take this as a reason to use composition, or a reason to discourage it's use in the border cases you note, so as to encourage learning and growth. All else being equal, I tend to go with self-typing just for verbosity reasons. Not much help here, I'm afraid, which is why it's a comment rather than an answer. Excellent question.Trachyte
Have you found the satisfactory answer?Eadwine
I've got some philosophical answers without technical precision that should be used in computer science. May the question itself is inappropriateDichromaticism
Can you put those philosophical answers over here? It will be of great help.Eadwine
You have covered most of it in your answerDichromaticism
E
3

Hints below are derived from heuristic approach (trial-and-error method of problem solving used when an algorithmic approach is impractical) and not supported by any formula (Mathematically -based reasoning).

***Hints given here should be evaluated in reference to accompanying hints, no hint is a perfect rule to distinguish composition and self-typing use-cases.

(While following below mentioned hints, I don't care or focus on verbosity or number of lines of the code or programming effort inputs.)

composition (dictionary meaning): the act of combining parts or elements to form a whole (Trivial Composition)

trait (Dictionary meaning): a distinguishing characteristic or quality

Hints for Trivial Composition (which can be achieved by super - sub class mechanism or association relationship) (e.g. Car and Wheels):

  • Which can be counted discretely (eg. Wheels)

  • Which can be classified futher ( based on different criterias) (eg. Wheels - alloy wheel, steel wheel etc)

  • Which can be added or removed (Note: When we say wheel stopped, it is actually wheel's rotation speed is stopped, when we say heart stopped, it is actually heart's pulsating speed has become zero)

  • generally applicable to few (in the universe Some Vehicles and some machineries have wheels) ( few can be 10- 15 or millions also - To explain let us understand the statement: when geologist talk about time and say some time ago , it means few million years ago, it depends on the actual subject)

Hints for Self Type (Trait)(eg. Car and Speed):

  • Which is unidimensional (not in terms of physics), can be plotted on a number line (whatever the physical unit is) (e.g. Speed)

  • Which can't be classified further naturally (e.g. Speed) (or atleast you will not classify it further) Here, naturally word used to convey the meaning that to classify it you will have to depend on your own criteria and there will be a definite possibility of classify it into millions of sub types. Take move, you can have millions of move sub traits ... like zigzag move, rotate and go forward,... (million possibility with various permutation combination).

  • Which can be increased or decreased or stoped (eg. speed, anger, love etc.)

  • Which is generally seen/ can be seen in very distantly placed classes (e.g. Speed of light, Speed of earth, speed of runner)

  • generally applicable to many ( in the universe majority (here every) object has speed)

    Software Development is like making your own universe and as a creator you define everything. A Trait will be seen among distantly placed classes in your domain (your own universe).

Please note that I have not seen any specific word (here counterpart for trait) in any language ( I know very few) for part which is used for Trivial Composition.

Further Explanation:

To get the answer you need to find somewhere deep in the philosophy of class oriented or object oriented aporach of software development and need to understand the mind and logic of the creators of the programming languages such as java and scala (or many more) which have inculcated class oriented or object oriented paradigm within those language.

Another thing you need is the deep understanding of semantics (the study of meaning or the study of linguistic development by classifying and examining changes in meaning and form )which we use to describe the real world and the semantics behind the keywords (in the programming language) we use as programmers.

I believe, when we create class we want to manifest the real world into software. The class becomes representation of something from the real world may it be car, human, star, dream, thought or imagination etc.

When somebody says "Wheels", you will have clear cut picture of its shape and application and you can think of driving wheel or wheels which roll on road. Wheel always be part of something. It can be counted in discrete numbers. Wheels can be further classified based on criteria like material, application, size etc. Wheel like things qualify for Trivial Composition.

When somebody says "Speed", you will not have any clear cut picture of it... no shape ...no colour... but you can relate it with any moving (relativity) part in the universe. It is a characteristic, trait. Speed is not part of anything. It can be there or it can not be there. It can be plotted on a single line (either direction + or - ). It is hard to classify "Speed". Speed like things qualifies for trait.

In my opinion,

If we take Car as a class (Object), "Speed" like characteristics should go as trait in scala. And "Wheel" like parts, components should go in as "Trivial Composition". "Speed" like characteristics will not have natural classification, where "Wheels" can have many classes and they themselves are independent objects (in reality).

If we take Human as a class (Oject), "Anger, crying, laughing, etc." like behaviors should go as trait and "hands, legs, brain, heart, etc." should go in as "Trivial Composition" as they themselves are independent objects (in reality).

If we think of name, it can be given to anything and anyone i.e. our nearest star has a name "Sun", highest mountain has a name "Himalaya", my dog has a name "Rocky", the river has a name "Amazon".... "Name" is a trait and should not be considered for "Trivial Composition".

If we think of heart, animals have heart as their part. It must be considered for "Trivial Composition" and not as a trait.

What is class?

Class is a description or a blue print of a particular Object.

What is object?

Object is a reality which can be described by the class definition.

(Egg or hen? Which came first?)I believe, Software engineer first thinks of Objects and then (to describe them or make them) (from a blueprint) defines class. (Please note that IN Object Oriented Modelling and Design - Class and Object are complementing each other's existence.) ( "Egg or hen? Which came first? is for co-existence of class and object and has no relevance with the famous Circle-Eclipse Problem (http://en.wikipedia.org/wiki/Circle-ellipse_problem) as the later is related with Inheritance or subtype Polymorphism.)

interface: a thing that enables separate and sometimes incompatible elements to coordinate effectively

Software Development is like making your own universe and as a creator you define everything. Composition should be preferred over Inheritance. ( Gang of Four - Design Patterns)

Eadwine answered 17/6, 2012 at 17:12 Comment(11)
the point "which can be classified further" work for trait ans self-typing as well. e.g. we use trait movable and subtraits that defines strait move, swirl move and so on.Dichromaticism
being able to stop is much more for composition than self-typing. part of you can't cease to work (as human can't live on with stopped heart).Dichromaticism
there is great difference in child-parent relation. If parent built in two parts via composition that have methods size() it can calculate total size as max(a.size(),b.size()) or a.size()+b.size() and so on. If this case is covered with self-typing all parts are equal and should use stackable trait patternDichromaticism
> "Object is a reality which can be described by the class definition. (Egg or hen? Which came first?)" It's quite doubtful since not all of real-life relations can be equally expressed in terms of OO programming language, see the famous ellipse-circle problemDichromaticism
Class may be instantiated. Trait requires only one more string to extend anonymous object with a trait. Classes and traits don't dedicate them to a data or an behaviour they both encapsulate data with behaviour.Dichromaticism
The main difference between class and trait is that class encapsulates constructor and trait require explicit companion object to be defined with apply and unapply methods. same object may be defined for a class but it not compulsoryDichromaticism
@Dichromaticism First of all I am talking in reference to pure Object Oriented Modeling Concepts because considering of USE CASES is the stage independent of any programming language."Many object systems in popular use are based on a design which takes it for granted that an object carries the same type over its entire lifetime, from construction to finalization. This is not a limitation of OOP, but rather of particular implementations only." Try and understand my statement: "Software Development is like making your own universe and as a creator you define everything".Eadwine
I catch you point. However scala can't be called pure OOP language. Trait language feature is a step aside in direction towards aspect-oriented modeling conceptsDichromaticism
@Dichromaticism Kindly note that I am not able to express my ideas so effectively because English is my third language. While answering, I am leaving holes because I don't know some appropriate English words.Eadwine
I haven't mastered English enough to give it any position in my languages list. So I have no problems in understanding your words. The problem is scala itself. It something more than java I believe and in this position scala may not accept all techniques applicable in javaDichromaticism
If forty years of object-oriented programming have taught us anything, it's that poetic folk ontology is a poor substitute for rigorous, mathematically-based reasoning about programming languages.Trachyte

© 2022 - 2024 — McMap. All rights reserved.