Tuesday, October 23, 2007

AOP vs IoC/DI???

An explanation to a colleague today that may be easier to understand than the typical ambiguous answer that he had recieved: "oh yeah its when you want to shove something in from the side"

AOP is different to IoC or Dependency injection (which is what Object Builder is) and can be used in conjunction with it.

IoC lets you code to interfaces and create object instances at runtime by calling the IoC Container (or dynamic factory) at runtime with the string key or Interface, to give you a concrete implementation of that interface (or sometime base class).

Spring.net and Windsor/Castle are the most popular open source IoC Containers and they both kind of do AOP as well, but it’s a bit convoluted.

Most people use AOP for “cross cutting concerning”, things like Logging, Security, Exception handling where you want a standard way of handling these things up and down the stack. The problem is that often at each tier, or even layer you get different people doing different things and it also mean you have code bloat like:

Public void MethodX(Type1 param1, int param2)
{
Log.(“enter MethodX);//Logging
Check.UserCanDo(MethodX);//Security
Try
{
Check.Ensure(param1 != null,”param1 can not be null”);//DBC
Check.Ensure(param2 > 10,”param2 must be greater than 10”);//DBC
… //Business logic
}
Catch(ExceptionY ey)//Exception handling
{
GlobalExceptionHandler.DoStandardExceptionHandling(ey);
Throw;
}
}

Where that whole thing can now be refactored to:

[StandardPublicMethodAOPHandler]//Logging, Security, Exception handling
Public void MethodX()
{
Check.Ensure(param1 != null,”param1 can not be null”);//DBC
Check.Ensure(param2 > 10,”param2 must be greater than 10”);//DBC
… //Business logic
}

Even better you can put that attribute on the method/class/assembly and then the normal devs don’t even have to worry about following standard procedure and code is a whole lot easier to read.

HTH. :)

No comments: