Have you heard about AOP? AOP stands for Aspect Oriented Programming - paradigm of software development focused on separation of so-called "concerns". What’s “concern” (in this context)? It’s a part of code that’s not related directly to functional requirements but it’s crucial for overall solution architecture and can’t be missed. Examples? Logging, transaction management, authorization and general security, multi-threading, exception handling, undo/redo, etc. Do you get the idea now? Code related to those “concerns” appears frequently and in a lot of places - it kinda interweaves with functional code and that makes it hard to maintain (as it can’t be separated if you stick to functional paradigm of software development).
AOP addresses this issue - it lets you define a desirable behavior once and “bind” it to “circumstances” related to the “concern” you want addressed. Sounds abstract? Ok, let’s try that in .NET.
The best known AOP solution for .NET is PostSharp (http://www.sharpcrafters.com/). What is it able to do? For example:
- Attach behavior to method (on: entry, success, exception, exit)
- Intercept method (intercept its execution)
- Attach behavior to property (on: set, get)
- Attach behavior to events (on: add handler, remove handler, invoke)
- Attach behavior to attribute
How could we attach those behaviors / intercept control? Oh, there are several ways to do that:
- By modifying the code - adding the custom attribute
- By adding it on the assembly level (assembly directive)
- By using Reflection
- By using inheritance (if aspects are already bound to parent level entity)
Looks like plenty of options. Doesn’t it? But, what’s the price? Are there any drawbacks? Indeed. You could make your app behavior less clear and harder to test (mainly, if you overuse AOP in a wrong way). One, tiny aspect can dramatically affect the overall performance of your whole application (because it will be executed for every “occurance of concern” - for instance, every exception, every method execution logging etc. On the top of that - PostSharp isnt’ free - you’ll need to pay for using it (excpet the free, limited Starter Edition).
Wanna see more? Check this article about large-scale multi-threaded applications using PostSharp: