The Cake Pattern  

The big question here is whether this thing is a steaming pile, something that we must incidentally support, or something that should be promoted.

The Cake pattern implements dependency injection. It also lets you share state amongst many components in a medium to large program without directly declaring a global variable OR passing it around.

Meaning it can clean up a lot of code, make it more clear, and make it truer in the communication of its intent. And it can also make "global" variables much simpler to implement and use.

Cake is clearly very useful for building balls of mud, since it makes the "pass your globals around" idea really easy.

I have built a ton of cakes, and you probably have too. They are less clean in languages that don't support mixin composition and virtual type members--you tend to be reduced to passing a single concrete type around that represents the "injected" dependencies, so there's no injection. These apps would undoubtedly be cleaner if there were an explicit dependency relationship between the components.

It's marginally better than having actual globals because, at some level, you always retain the ability to create multiple instances of your program.

As Scalable Component Abstractions notes, "what is a complicated system on one level might be a simple element on the next level of scale".

Perhaps what is most valuable about cake is the scoping. You can place whatever state you need at whichever scope level it corresponds to without ever being reduced to something "static". Everything is instantiable.

Comments powered by Disqus