Om mig

Mitt foto

I'm a software developer playing around with Scala, Lift and GWT along with a few DIY side projects.

söndag 6 maj 2012

Problems with the Scala Cake Pattern - aka. Too much cake


A popular way to do dependency injection in Scala is to use the Cake pattern (see Jonas Boner's excellent blogg post about it). This pattern involves specifying components using traits and specifying dependencies by using self-types. My main problem with the cake pattern is that it is very verbose. To illustrate let's look at how we can use dependency injection in Java using Spring:
This is 20 lines of code for a FooService that depends on a FooDao. To get this to work we would also need a few lines of XML configuration to enable component scanning etc.

If we instead use the cake pattern we get the following.

This version is 25 lines of code. Sure, a separate xml file for the wireing is no longer necessary, we can just do: But, the problem with the verbosity still remains. The java sample consist of 20 lines whereas the scala code is 25. I believe most developer would agree that Java is a very verbose language, despite this it is still more concise than the scala equivalent! That should ring an alarm bell. If we instead of java decided to use scala in the annotation driven way then we could shrink those 20 lines even further. While this might be ok if the proportions in LOC shifted when adding more components, but it does not. As we add more and more components the boilerplate necessary will further increase the difference!

Of course LOC is not the whole story. We should also ask ourselves about the readability of the code. I have been using Spring quite a bit at work so my opinion is obviously biased because of it and I have not written alot of code using the cake pattern, but I think that the java/spring version is clearer. Also, you would likely end up having to specify all the vals and methods as protected in case you do not want to expose all the parts of the final component.

To summarize the Cake pattern makes our code verbose and (to me) hard to read due to the boilerplate necessary. I also see some other minor problems with the pattern, but my main concern is that it adds a lot of noise to the code base.

Should we just ditch the cake pattern and revert to using a DI framework like Spring? No. At least, I do not think so. Spring brings with it a bunch of fantastic features, but DI in Scala can be solved in a clean manner using some other language features. I will make a post about it next.

Inga kommentarer:

Skicka en kommentar