Using mixins in Java

Thameena S
3 min readJun 20, 2020

Often we like to attach abilities to our class but it is mostly done as a delegate and not as a mixin in Java.
We will explore in this blog on implementing mixins in Java using first class collections.

First class collection means a collective object is given domain importance. It has to behave as a collection as well as a domain object.

Rule 4: Object Calisthenics by William Durand

Any class that contains a collection should contain no other member variables. If you have a set of elements and want to manipulate them, create a class that is dedicated for this set.
Each collection gets wrapped in its own class, so now behaviours related to the collection have a home (e.g. filter methods, applying a rule to each element).

Consider an example for a publication domain with two classes, Magazine.java and Newspaper.java which will have a list of subscribers. The usual idea would be to model it like this:

Magazine.java
Newspaper.java

Notice that all the operations on list of subscribers have been duplicated in both the classes. Also, wouldn’t Magazine.java and Newspaper.java become a little too overcrowded , when you have a lot of fields and methods?

Here comes the idea of first class collections. List of subscribers can be given domain importance by making another class Subscribers.java which will have List<Subscribers> as a field inside it.

Subscribers.java

Now how do we make Subscribers.java behave as a List? We can, by making Subscribers implement List. But that would mean implementing all the functions of List in Subscribers, and you will end up getting a long class with all the functions of List and Subscribers in one single class. A better approach would be to separate out the behaviour of List and implementation ofSubscribers into separate classes. Lets try implementing an interface, that will extend the List interface.

ListMixin.java

When you design something like this, you will have to override existing List functions to operate on your custom arrayList. Here is a snippet of how this will look like.

ListMixin.java

Now coming back to Subscribers.java, we can have this class behave like a list by implementing ListMixin interface and overriding the getRecords() method to return the list of subscribers. All your operations on the list of subscribers will go into this class.

Subscribers.java

No more code duplication in Magazine.java and Newspaper.java now.

Magazine.java

Now, neither Magazine.java nor Newspaper.java will have to handle the logic of returning the list of subscribers who are prime users. Notice how code duplication has been avoided in both the classes. These classes will now be shorter and pull in all the necessary functions from our first class collection.

--

--