Saturday, May 24, 2008

Google Guice and Xuices in General

Google Guice is a framework library that helps you implement certain design patterns like factories easily and elegantly. The Guice user guide and the tech talk video are recommended to get started with. I did start with them, but somehow, that felt short of giving the 'aha!' moment. A nice series of articles in four parts (Juicy Code with Google Guice in parts 1, 2, 3, 4, and 5 led me on to think further.

Finally I realized, which many of you more active into this domain might realize earlier, that Google Guice is useful no doubt, but that is just the tip of the iceberg. It is essentially AOP (Aspect Oriented Programming) using Java Annotations and code injection.

AOP in essence allows code to be broken up into modular functionalities, which are called concerns or aspects, that can then be injected into other places of the code easily. Typically concerns that are crosscutting are candidates for aspects, e.g., logging, security, transactions, or in a large application any typical behavior/pattern used quite frequently throughout. Most of the times these do not have anything to do with the core issue being addressed in the current module, but are necessary things to be done. Fundamental constructs thus isolated and reused make the remaining code simpler to develop, understand, test and debug. That is what Guice does, isolating the addressed concern and making it easier for you as a user.

You can also make your own Xuice! Java has Annotation Processors that can be used to either generate code at compile time, branch out differently at run time and even generate bytecode to create and load new classes at run time. Using a powerful byte code manipulation library (maybe using Apache BCEL) you can inject or modify the byte code during class loading. The following java.net articles make good reading in this direction: