Which situations require AspectJ, you ask. Imagine the following scenario: you're a member of a development team facing a huge project that a number of clients are going to buy, but each client has a few requests for the project. One needs logging functions in 10,000 specific places within your code. Another requires some very specific logging functions only for critical (from his point of view) parts and situations. A third client requires added networking, localization, etc.
Of course, you could rebuild the project's structure, adding new functions with new configurations, creating new class dependencies, and so on, but since the project is already in development, you are under time pressure (as usual). Maybe add "hardcoded" patches? Yes, but a "patched" project likely will get out of control very quickly. Besides, it also requires testing, bug fixing, etc. Doesn't that all sound like a real headache? Not with AspectJ. You can create aspects, which will do everything necessary.
Aspects are the essence of AspectJ. In general, an aspect is a modular unit that crosscuts the structure of other modular units. It exists in either design or implementation:
- A design aspect is a modular unit of the design that crosscuts the structure of other parts of the design.
- A code aspect is a modular unit of the program that crosscuts other modular units of the code.
This is a very general definition that doesn't address OO, but suites the introductory purposes of this article. Aspects can have type, extend classes and other aspects, and be either abstract or concrete. They do not have constructors or finalizers, cannot be created with the new operator, and cannot be used interchangeably with classes. For more detailed info, consult the official documentation. However, here's a brief listing of some of the things you can do with aspects:
- Place code before or after a method call
- Change method arguments
- Track method calls using regular expressions
- Change class hierarchies
- Control the treatment of exceptions
Getting back to your project, even if you've never worked with AspectJ, you can easily recognize the advantages it would offer:
- You can place additional code around method calls to provide logging.
- To separate these logging, localization, or networking functions (it doesnt really matter for which function type you use your aspects) among your customers, you can track your methods with regular expressions, which AspectJ uses.
- And the main advantage: none of these features will require any code updates. You can just create new aspects and recompile the project.