Posted on by & filed under Content - Highlights and Reviews, Programming & Development.

A guest post by Matthew D. Groves, author of AOP in .NET, and also teaches at Capital University.

The single responsibility principle states that a class should have only one reason to change. It should do one thing, it should do it well, and it should do only that one thing. Consider a class with one method for reversing strings:

This is contrived, but there is no doubt that this class and its one method has only one responsibility. Unfortunately, this type of code doesn’t make it into production as-is. Cross-cutting concerns are often scattered throughout otherwise single responsibility code: logging, threading, caching, and exception handling, just to name a few.

Consider a requirement that every method call must result in log entries for the method name, date/time called, return value, arguments passed in, and so on. This may sound absurd, but there may be a number of good reasons—business or technical—for this requirement. Consider a naive approach to this feature:

This approach solves the problem, but the flaws should be obvious: production applications contain hundreds or thousands of methods, and adding all of this logging code would take a considerable effort. Here’s another approach that attempts to use reflection to cut down on the repetition:

You can use the MethodBase object to dynamically log the method name and the parameter names/types without having to handcode that information for every method. But this approach isn’t much better than the naive one. We still have to copy and paste the call to Log.WriteMethodInformation into every function. Also, note that this approach doesn’t completely fulfill the requirement, since there’s no way to get the arguments or return values using reflection, so we’ll still have to go back and hand code that logging.

Another approach is to use a subclass:

In this example, I used the new keyword to hide the base class method, and then call it from within. Another, preferable, approach would be to make the base Reverse method virtual and then use override instead of new. This subclass approach may be helpful in some situations with extensive default behavior, but I think a better approach for cross-cutting concerns is to use the the decorator pattern:

This allows you to add functionality to StringReverser without having to change StringReverser, except I gave it an interface, which it should probably have anyway. You can also add multiple levels of decoration. A logging decorator, a caching decorator, a security decorator, and so on, can all be stacked up in the same “pipeline” to add cross-cutting concern functionality without changing a single line of the “target” class.

The weakness of the decorator pattern, as far as cross-cutting concerns, is that each decorator is unique to an interface. It can’t be re-used with other interfaces, in other layers, and so on. So you’d have to write very similar (and repetitive) decorators. It’s not the end of the world, but wouldn’t it be nice if we could just write that chunk of boilerplate once, and let some other tool generate the decorators for us? That’s basically what AOP is: a way to automate design patterns. Read What is AOP? in AOP in .NET: Practical Aspect-Oriented Programming for more information.

Here’s an example with PostSharp, a .NET AOP tool:

To apply this aspect, PostSharp uses .NET Attributes (for instance, using [LoggingAspect] as an attribute on the Reverse method would do the trick) to signal to a post-compile process where to weave the aspect.

If you wish to apply logging to any method, simply put the [LoggingAspect] attribute on it. With PostSharp, attributes can be multicast in a number of ways to avoid repetition. This example applies the logging aspect to every method in every class within a certain namespace:

Other AOP frameworks like Castle DynamicProxy, Spring.NET, Fody.MethodDecorator, and so on, have a very similar method interception API. AOP tools either generate proxies at runtime using Reflection, or they manipulate IL at compile time.

The end result is that the code for performing the logging lives in one completely encapsulated class, and the code being logged can be changed at will without affecting the completeness of the information being logged.

Conclusion

When the main code changes, the logging code doesn’t need to change, and when the logging code changes, the main code doesn’t need to change. Each class has one and only one reason to change. Each class does one thing, does one thing well, and does one thing only. Below are some AOP resources found in Safari Books Online.

Safari Books Online has the content you need

AOP in .NET: Practical Aspect-Oriented Programming by Matthew D. Groves, the author of this post, introduces aspect-oriented programming to .NET developers and provides practical guidance on how to get the most benefit from this technique in your everyday coding. The book’s many examples concentrate on modularizing non-functional requirements that often sprawl throughout object-oriented projects.
Programming Grails helps experienced web developers learn Grails best practices for building and deployment, debugging and problem solving, creating and using Grails plugins, as well as testing, security, performance, scaling, tuning, and monitoring. Take a look at the chapter that covers AOP in depth.
AspectJ in Action is a fully updated, major revision of Ramnivas Laddad’s best-selling first edition. It’s a hands-on guide for Java developers. After introducing the core principles of AOP, it shows you how to create reusable solutions using AspectJ 6 and Spring 3. You’ll master key features including annotation-based syntax, load-time weaver, annotation-based crosscutting, and Spring-AspectJ integration. Building on familiar technologies such as JDBC, Hibernate, JPA, Spring Security, Spring MVC, and Swing, you’ll apply AOP to common problems encountered in enterprise applications.

About the author

mebricks Matthew D. Groves is a guy who loves to code. It doesn’t matter if it’s “enterprisey” C# apps, cool jQuery stuff, contributing to OSS, or rolling up his sleeves to dig into some PHP. He has been coding professionally ever since he wrote a QuickBASIC point-of-sale app for his parent’s pizza shop back in the 90s. He currently works from home on the Telligent product team, and loves spending time with his wife and 2 kids, watching the Cincinnati Reds, and getting involved in the developer community. He is the author of AOP in .NET (published by Manning), and also teaches at Capital University in Columbus, Ohio. He can be reached at @mgroves, and on G+.

Tags: .NET, AOP, Aspect-Oriented Programming, automate design patterns, Castle DynamicProxy, Grails, single responsibility principle, Spring.NET,

Comments are closed.