I am trying to understand the separation of concerns used within AOP. Therefore i would appreciate if someone could explain me what does mean code scattering and code tangling in AOP using some basic HelloWorld examples. How would i know afterwards if a given concern is not a system-core concern but rather an aspect? Many thanks.
I'm afraid I'll use logging as an example, which is the one we always use, but I hope it makes it easy to understand. Consider this helloworld program with logging:
public class HelloWorld {
private static Logger logger = Logger.getLogger(HelloWorld.class);
public static void main(String []argv) {
logger.entering("HelloWorld","main");
System.out.println("Hello World");
logger.exiting("HelloWorld","main");
}
}
My class only has 8 lines (ignoring whitespace) - 3 of them are logging, almost half! Logging has nothing to do with the primary goal of this class which is to print Hello World
. Logging is tangled up with the primary goal of this class. If we could remove it and express it another way then we'd have half the code and what the class is primarily trying to achieve would be even clearer. Additionally being tangled up may harm capabilities like reuse - this code can't be used to print helloworld without it doing some logging and needing some kind of logging infrastructure around.
Now consider a real system where there are multiple classes, and they are all doing logging. Now suppose I decide I want to change one of the logging methods I'm using - I want all my calls to entering
changed to info
and to include some extra information. Nightmare! My logging is scattered across my codebase. There isn't one place to make this change, there might be thousands.
If I captured that scattered, crosscutting concern in an aspect, there would be just one place to make the change.
Identifying what might be an aspect:
Scattering can be a small scale concern. Maybe every method in one of your classes is repeating some pattern, but no other classes are using it. No harm in creating a small aspect for the class that just addresses the scattering within those methods.