In the java world (more precisely, if you do not have multiple inheritance / mixins), the rule of thumb is pretty simple: "Use the composition of objects over class inheritance."
I would like to know if / how this has changed if you are also considering mixins, especially in scala?
Are blends considered a multiple inheritance method, or a more cool composition?
Is there also an “Object support structure over a class” (or vice versa)?
I saw several examples when people use (or abuse) mixins, when composing an object can also do the job, and I'm not always sure which one is better. It seems to me that you can achieve quite similar things with them, but there are some differences: some examples:
- visibility - with mixins everything becomes part of the public api, which does not correspond to the composition.
- verbosity - in most cases mixins are less verbose and a little easier to use, but this is not always the case (for example, if you also use self types in complex hierarchies)
I know that the short answer is: “It depends,” but there is probably a typical situation where it is or is better.
Some examples of recommendations that I could come up with so far (if I have two traits A and B, and A wants to use some methods from B):
- If you want to extend API A using the methods from B, then mixins, otherwise composition. But this does not help if the class / instance that I am creating is not part of the public API.
- If you want to use some patterns that need mixes (like the Stackable Trait Pattern ), then this is a simple solution.
- If you have circular dependencies, mixins with self types can help. (I try to avoid this situation, but it is not always easy)
- If you need any dynamic runtime solutions, how to execute composition, then the composition of the object.
In many cases, mixins seem lighter (and / or less verbose), but I'm pretty sure that they also have some pitfalls, such as the “God class” and others described in two articles by artima: part 1 , part 2 ( By the way, it seems to me that most of the other problems are not related / not related to scala).
Do you have more such tips?
scala mixins composition
Sandor Murakozi Aug 6 2018-10-06T00: 00Z
source share