I came across google guice and could not really understand it and what it did, although there seems to be alot of hype around it. I was hoping to get a clojurian perspective of the library and why it is needed/not needed in clojure applications and if there was anything similar built into the language.
Google Guice is a dependency injection framework that you can use with an Endpoints Frameworks v2 project to configure servlet mapping and filtering programmatically in Java, rather than in web. xml . To use Guice, you need to add the following prepackaged dependency to your pom. xml or build.
Beyond Dependency Injection, the benefits of using Google Guice is: Guice has a very clean implementation of constructor Injection. As you can see from the example you just add @Inject annotation constructor. Guice also has setter Injection using the same annotation.
Guice Basic Bindings. Binding is to Guice as wiring is to Spring. With bindings, we define how Guice is going to inject dependencies into a class. This module implementation specifies that an instance of DefaultCommunicatorImpl is to be injected wherever a Communicator variable is found.
Because of Java's OO and type system, dynamically switching between different underlying implementations (for test (mocking) purposes for instance) can be difficult to manage. Libraries like Google Guice are intended to handle these dependency injections in Java more gracefully.
In Clojure and other functional languages functions can be passed around, which makes using different implementations much easier.
There's several ways this can be done in Clojure:
Chapter 12 of Clojure Programming has some nice examples of OO patterns like dependency injection and the alternative ways to handle these in Clojure.
Sean Devlin also has a Full Disclojure video on Dependency Injection in Clojure. His example might have been chosen better, though. Instead of using completely different function implementations in his closure, he uses a factory that returns different 'versions' of a function. The gist stays the same though.
Basically, dependency injection is a pattern that is a necessary evil in OOP, and can be solved easily (or is not even a problem) in FP.
The rough Clojure equivalents are still in development. There are two libraries currently in development (as of Oct '12): Prismatic's Graph (not yet open sourced) and Flow by Stuart Sierra.
Note that I consider Guice to be more than dependency injection. It provides a framework for application configuration / modularization. The above libraries aim to accomplish that goal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With