CocktailJS is a NodeJS module to explore concepts such as Annotations, Traits, and Talents aiming to improve code reuse and organization.
There are several ways to reuse code. In general, most developers tend to abuse the classical inheritance and grouping common behavior in parent classes. This often leads into a very deep inheritance tree and, usually, to have many *Abstract* or *Base* class names.
There are several articles describing the benefits of using Mixins. A mixin can be seen as a mechanism to implement multiple inheritance (hence, they have the same issues as other languages that support multiple inheritance). A couple years ago, the concept of Functional Mixins arose. The idea, is to share behavior across classes or data types - I believe is a better name - solving the problem of who is responsible to initialize the mixin properties by just avoiding them. But, we still have the problem of multiple methods definition. When you apply a mixin that contains a method
foo, and the class also contains another
foo method, there is no clear rule about which one will be in the result.
By definition, a Trait cannot contain state, this means that only behavior (methods) can be defined in a trait. An interesting aspect is that in case of a method name collision there is no magic rule or precedence and it is a developer responsibility to solve that scenario in code.
There are not one but two ways to solve name collisions with Traits. One is to exclude the method definition from a given trait. Another mechanism is to create an alias for the method in case you want to use it later in your class definition.
CocktailJS is available to download from npm:
$ npm install cocktail
› Any viewpoints and opinions expressed in this article are my own and do not, in any way, reflect those of my employer, my colleagues, or anyone else. I speak only for myself, not for them.