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?
To get the higher design flexibility, the design principle says that composition should be favored over inheritance. Inheritance should only be used when subclass 'is a' superclass. Don't use inheritance to get code reuse. If there is no 'is a' relationship, then use composition for code reuse.
Composition is the design technique in object-oriented programming to implement has-a relationship between objects. Composition in java is achieved by using instance variables of other objects. For example, a person who has a Job is implemented like below in java object-oriented programming.
Composition is a concept that models a has a relationship. It enables creating complex types by combining objects of other types. This means that a class Composite can contain an object of another class Component . This relationship means that a Composite has a Component .
Aggregation in object oriented programming Aggregation is a specialized form of association between two or more objects in which each object has its own life cycle but there exists an ownership as well. Aggregation is a typical whole/part or parent/child relationship but it may or may not denote physical containment.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With