About Adam Warski

Adam is one of the co-founders of SoftwareMill, a company specialising in delivering customised software solutions. He is also involved in open-source projects, as a founder, lead developer or contributor to: Hibernate Envers, a Hibernate core module, which provides entity versioning/auditing capabilities; ElasticMQ, an SQS-compatible messaging server written in Scala; Veripacks, a tool to specify and verify inter-package dependencies, and others.

DI in Scala: Cake Pattern pros & cons

I’ve been looking at alternatives for java-style DI and DI containers which would use pure Scala; a promising candidate is the Cake Pattern (see my earlier blog post for information on how the Cake Pattern works). FP enthusiast also claim that they don’t need any DI frameworks, as higher-order functions are enough.

Recently Debasish Ghosh also blogged on a similar subject. I think his article is a very good introduction into the subject.

Below are some problems I encountered with the Cake Pattern. (Higher-order functions are coming up in the next post.) If you have solutions to any of them, let me know!

Parametrizing the system with a component implementation

First of all, it is not possible to parametrize a system with a component implementation. Supposing I have three components: DatabaseComponent, UserRepositoryComponent, UserAuthenticatorComponent with implementations, the top-level environment/entry point of the system would be created as follows:

val env = new MysqlDatabaseComponentImpl
   with UserRepositoryComponent
   with UserAuthenticatorComponent

Now to create a testing environment with a mock database, I would have to do:

val env = new MockDatabaseComponentImpl
   with UserRepositoryComponent
   with UserAuthenticatorComponent

Note how much of the code is the same. This isn’t a problem with 3 components, but if there are 20? All of them but one have to be repeated just to change the implementation of one component. This clearly leads to quite a lot of code duplication.

Component configuration

Quite often a component needs to be configured. Let’s say I have a UserAuthenticatorComponent which depends on UserRepositoryComponent. However, the authenticator component has an abstract val encryptionMethod, used to configure the encryption algorithm. How can I configure the component? There are two ways. The abstract val can be concretized when defining the env, e.g.:

val env = new MysqlDatabaseComponentImpl
   with UserRepositoryComponent
   with UserAuthenticatorComponent {
   val encryptionMethod = EncryptionMethods.MD5
}

But what if I want to re-use a configured component? An obvious answer is to extend the UserAuthenticatorComponent trait. However if that component has any dependencies (which, in the Cake Pattern, are expressed using self-types), they need to be repeated, as self-types are not inherited. So a reusable, configured component could look like this:

trait UserAuthenticatorComponentWithMD5
         extends UserAuthenticatorComponent  {
   // dependency specification duplication!
   this: UserRepositoryComponent =>
   val encryptionMethod = EncryptionMethods.MD5
}

If we don’t repeat the self-types, the compiler will complain about incorrect UserAuthenticatorComponent usage.

No control over initialization order

A problem also related to configuration, is that there is no type-safe way to assure that the components are initialized in the proper order. Suppose as above that the UserAuthenticatorComponent has an abstract encryptionMethod which must be specified when creating the component. If we have another component that depends on UserAuthenticatorComponent:

trait PasswordEncoderComponent {
   this: UserAuthenticatorComponent =>
   // encryptionMethod comes from UserAuthenticatorComponent
   val encryptionAlgorithm = Encryption.getAlgorithm(encryptionMethod)
}

and initialize our system as follows:

val env = new MysqlDatabaseComponentImpl
   with UserRepositoryComponent
   with UserAuthenticatorComponent
   with PasswordEncoderComponent {
   val encryptionMethod = EncryptionMethods.MD5
}

then at the moment of initialization of encryptionAlgorithm, encryptionMethod will be null! The only way to prevent this is to mix in the UserAuthenticatorComponentWithMD5 before the PasswordEncoderComponent. But the type checker won’t tell us that.

Pros

Don’t get me wrong that I don’t like the Cake Pattern – I think it offers a very nice way to structure your programs. For example it eliminates the need for factories (which I’m not a very big fan of), or nicely separates dependencies on components and dependencies on data (*). But still, it could be better ;).

(*) Here each code fragment has in fact two types of arguments: normal method arguments, which can be used to pass data, and component arguments, expressed as the self type of the containing component. Whether these two types of arguments should be treated differently is a good question :).

What are your experiences with DI in Scala? Do you use a Java DI framework, one of the approaches used above or some other way?

Reference: DI in Scala: Cake Pattern pros & cons from our JCG partner Adam Warski at Blog of Adam Warski.

Related Articles :

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


3 − one =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close