To make sure we have clean code and make it easy for us to
maintain, we should try to be lazy and reuse code as much as
possible, we should also avoid redundant code. But when it
comes to crosscutting concerns, we have to be redundant, or?
What code is mostly redundant in our code? I will assume that
code to check security and logging exceptions are the most
redundant code we write. A method should only do one thing,
but we can't skip crosscutting concerns, we need it. So
basically several method will do more than one thing. Wouldn't
it be much better if we only focus on the core concern and
skip the crosscutting concerns when we write our code? How can
we skip the crosscutting concerns but still has it? The answer
is Aspect Oriented Programming (AOP). The PAG team has a
Policy Injection Application BLock (PIAB) which we can use to
intercept our crosscutting concerns into our code, we also
have Spring.Net and some other frameworks. By using AOP
frameworks we don't need to write the same code for logging
exception etc over and over again, we will also have a much
cleaner code, and our focus will only be the core concern. Oh,
I feel so lazy, but why should I spend time to write code that
do the same thing over and over again, it's so boring, isn't
it :P Are you tired of writing crosscutting concerns over and
over again, and do you use AOP today?
4 Comments
I must say that I hardly ever write code for logging
exceptions throughout my code base. 99% of the time I
let the exceptions bubble up and have a catch all
mechanism on top of the (web) application that logs the
unhandled exceptions.
Is this a good time to plug my own logging framework?
Yes it is :-). CuttingEdge.Logging enables such a
catch-all mechanism: http://www.codeplex.com/logging.
I must admit that never use AOP frameworks. I hardly
need it for logging and for security I use the Roles and
Membership Provider Model of ASP.NET. There is however a
build in AOP security mechanism in .NET that I use
often. The PrincipalPermissionAttribute. This attribute
enables code access security on a user and role basis.
Next to that, while I consider AOP frameworks valuable,
they add a layer of complexity. Most of the teams I work
with, are less experienced and advising them to go with
AOP, wouldn’t be a wise thing, I believe. I think it
would be better if they spend time reading McConell’s
Code Complete 2nd Edition, for instance, instead of
using that time on mastering AOP.
Great post! Which framework do you currently use to help
with injecting your aspects?
@Mikael Deurell:
hi dude, I only had to write about this after our great
meeting ;)
@Torkel:
I agree!
@Jonathan:
Springt.Net, but I start to like Unity together with
PIAB.
Just to clarify my point of view:
Everyone that thinks that code mangling AOP is a good
idea needs to take a basic course on OOP.
That, or stop doing .NET and switch to Ruby ;-)