Concerns and Crosscutting Concerns
The first time I looked at AspectJ, it seemed like a foreign language, with its complex fog of mysterious terms such as aspects, join points, crosscuts, load time weaving, etc. I thought I had stumbled uninvited into a secret society called aspect oriented-programming (AOP).
In reality, AOP’s not so hard! In this article, I won’t go into too much detail on AspectJ—just enough, hopefully, to get you up and running with the example code. The help facility that comes with AspectJ is reasonably good and provides more detail on the background.
Before we get started on a simple example, let’s review what’s meant by the terms concern and crosscutting concern. A software concern (big issue) is basically a multi-module code area such as persistence (reading from and writing to disk or database), GUI, security, tracing, networking, and so on. Good design dictates that you should always try to separate concerns from one another—for example, don’t embed calls to GUI code inside code that handles JDBC (or ODBC). Overlapping concerns produces spaghetti code. Figure 1 illustrates this point about separation.
Figure 1 Some of the different concerns—good separation.
The concerns in Figure 1 are typical of the major issues in an application. The important point about these concerns is that they’re spread across the modules of your software. This is what’s meant by a crosscutting concern.
Crosscutting concerns are not new. They’ve always been around and they’ve always been difficult to handle—in both procedural and object-oriented languages. The reason is simple: In procedural languages, we use functions and data structures to implement the required concerns, whereas in object-oriented languages we use classes. If the design doesn’t properly separate concerns, the finished code structure can look more like Figure 2, where the concerns overlap.
Figure 2 Poor separation between concerns.
We’ve all worked on software with interacting and overlapping concerns, and we all know that overlapping concerns are a recipe for code that’s hard to maintain. The key point is that the more your code structure maps to something like that of Figure 1, the more maintainable your code will be. AspectJ allows you to more easily modularize crosscutting concerns by using aspects. Interestingly, AspectJ may help when you have to implement a new crosscutting concern in an existing large software product.
AOP isn’t a substitute for good design, but it can help in situations where a design team has produced a product that looks like Figure 1, but suddenly the marketing folks require the addition of a range of new crosscutting concerns. Rather than busting a gut hacking up the existing code structure, you can use aspects to implement the new required concerns. This is a production-time aspect, and I’ll discuss one of these shortly.