Inheritance + Mixins *with* another solution

In previous post i was talking about some alternatives to classical IoC/DI. I`m not here to argue whats bets or worst, the 2 approaches have advantages and cons. Most classical OO languages like JAVA and .NET tend to fix things at runtime. Java for instance all happens in runtime, spring context. JSF context, Hibernate/JPA context, reflection(memory), CGlib, proxies, etc..

In FP languages that are children of haskell like F# and Scala things tend to happen as much as possible close to the compiler and thats has good and bad things like everything in life. In java or .NET you dont have multiple inheritance like you do in C++. So another approach would be do inheritance and work with the ideas of Modules.

Some people call this: Thin Cake Pattern, for me is just multiple inheritance with syntactic sugar. As long as you do it only for classes/traits and dont do it for values i think is ok and IMHO cleaner than the cake pattern.


So lets see some scala code to make it clear what i`m talking about, consider the previous post scenario, so we have the Car case class, also the TaxService trait, now with a default implementation on the trait and them the brazilian implementation, as you can see i dont need to have the repositories everywhere and i endup with less code.  You may realize we have the Argentinian implementation as well but now both brazil and argentina have a lazy val its just a trick to do the overide of the method on the interface/trait.


The cool thing here is 3 things actually, besides the fact that you have less classes is:

1. The lazy will make it faster since only will called when is needed, so no overread for this approach.

2. you can use multiples *with* and do multiple inheritance with that or you can use that as a mechanism to do modules. and them you pick when you want use the module A, B or C or even mockedA or MockedB.

3. You can do that both inside of the class/type and external, so the caller can instantiate the default trait and pick the modules you want use (lines 40 and 41).

Classical Ioc/Di to setter/Constructor injection is ok, cacke pattern as well(but it make more classes) multiples inheritance with modules looks cleaner to me if you want be close to the compiler but remeber is inheritance in the end of the day so it could get messy.

Cheers.

Popular posts from this blog

Kafka Streams with Java 15

Rust and Java Interoperability

HMAC in Java