Unit Testing Gives Merit to Design Patterns

An entry about tdd | design patterns Publication date 8. December 2008 23:58

Son Hui has written a post in which he shows how using TypeMock helps him mock the SmtpClient class. At the beginning of his post, he writes:

“The proponents of TDD would like to use Dependency Injection(DI) technique to inject the SmtpClient dependencies into the mail sending class in order to facilitate unit testing.“

I would much rather say that the reason we do dependency injection is to achieve what is called the dependency inversion principle. I think this is one of the biggest misconceptions a lot of people have when faced with unit testing: the idea that in order to make code testable, they have to apply all of these academic design patterns. But, isn't´t just the fact that these design patterns makes code easier to test just more proof that they actually work?

Go SOLID today.

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

DataContext Repository Pattern Example Code

An entry about linq | design patterns Publication date 27. September 2008 11:25

Since writing my post on abstracting the Linq to Sql DataContext, I’ve had several requests to post an example project which shows exactly how this works. I finally found some time to do just that – click here to download it!

In the zip file you’ll find the Devin.Core project (Devin is the name of a small start-up I’m involved in), which contains the current version of my DataContext abstraction, as well as the specification pattern implementation that I’ve written about earlier (which by the way is not really finished yet – I’m still planning to pursue this further when I get some time).

To show how it works, I’ve included a simple console application that you can play with.

Currently rated 5.0 by 7 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

ASP.NET MVC, DataContext and The Unit of Work Pattern

An entry about asp.net mvc | design patterns Publication date 17. May 2008 15:33

Previously, I talked about the Repository pattern and how we could implement it using Linq (and Linq to Sql in particular). This week, I'd like to take the Linq Repository abstraction that I came up with last time, and show how we can use it to easily and transparently enable the Unit of Work pattern, using ASP.NET MVC as our host.

What's in a Unit

From Fowler, a Unit of Work "maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems" (PEAA, p. 184). The key here is that "unit" means "business transaction".

The Linq to Sql DataContext is designed perfectly to support this pattern. In fact, the MSDN documentation for it plainly states that "a DataContext instance is designed to last for one "unit of work" however your application defines that term. A DataContext is lightweight and is not expensive to create. A typical LINQ to SQL application creates DataContext instances at method scope or as a member of short-lived classes that represent a logical set of related database operations." .NET consultant and author (MSDN Magazine) Dino Esposito emphasises this point in an in-depth article over at DotNetSlackers, and also in a follow-up post on his blog.

One Request = One Action = One Unit of Work

The beauty of an MVC application, is that each request is self-contained. There's no state to worry about; each request has all the information it needs to carry out the requested action. This fits neatly with what we've just discussed - we can then say that each request, or action, is in fact a single unit of work.

I've talked about how to set up the IOC container Autofac for ASP.NET MVC before, so I won't reiterate that here. The cool thing about Autofac, is that it allows for nested containers. In fact, its ASP.NET integration module will out of the box set up a root container that is application scoped, and then a new nested container for each new request. All we have to do then, is to register our IDataContext as a container scoped object. Autofac will then ensure that throughout the lifetime of any request, any object that asks for it gets the same IDataContext instance injected:

builder.Register(c => new DataContext(ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString)).FactoryScoped();
builder.Register<LinqToSqlContext>().As<IDataContext>().ContainerScoped();

 

Notice that I've registered the concrete DataContext class as well - this is so that Autofac will know how to resolve the constructor for my LinqToSqlContext, which takes a DataContext as its single parameter.

Any controller class that has actions which require access to the unit of work can then be implemented like this:

public class EditController : Controller
{
    private readonly IDataContext _unitOfWork;
 
    public EditController(IDataContext unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }
 
    public ActionResult Rename(string route, string newTitle)
    {
        IPage page = _unitOfWork.Repository<IPage>().Where(p => p.Route.Path == route).Single();
        page.Title = newTitle;
 
        return new RenderJsonResult {Result = new {status = "ok"}};
    }
 
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        _unitOfWork.Commit();
    }
}

 

Note that I would probably move that OnActionExecuted method to a base controller type to avoid duplicating it in all my controllers. And also note that because of the deterministic disposal functionality of Autofac, we don't have to worry about disposing the IDataContext; it (and the Linq to Sql DataContext it wraps) will be disposed with the nested container at the end of the request.

I think the power of design patterns really shows when you see how well different technologies that adhere to them are then enabled to work together in perfect harmony, like here.

Currently rated 4.2 by 6 people

  • Currently 4.166667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Linq to Sql, Programming Against an Interface and the Repository Pattern

An entry about tdd | linq | design patterns | domain-driven design Publication date 5. May 2008 21:56

Program against an interface, not an implementation. I've always been a big fan of that saying. Obviously, in this context interface doesn't necessarily mean an actual interface type; maybe it should have been written as "program against an abstraction, not an implementation" to make that clear. With Linq to Sql - and really most O/R mappers out there that do code-generation - this pretty much goes out the window since you're leaving the O/R mapper in charge of generating the code for the domain model objects for you, based on some (database) schema. What you end up with as a consequence of this, is code like:

var query = from pages in dataContext.Pages where pages.IsPublished select pages;
 
foreach (Page page in query)
{
    // do something with page...
}

 

Here, I'm not programming against an interface - I'm programming against the explicitly implemented Page class. My strongly typed DataContext, autogenerated by the O/R mapper (Linq to Sql), exposes a property Pages which is of type Table<Page>. What I want, though, is an interface IPage that everyone (apart from the factory creating the instance, obviously) should program against; they should never touch the actual Page type.

Partial Rescue

Thankfully C# has got what it takes to solve this, we just have to jump through a few hoops for it. When SqlMetal generated the Page class it made it partial, which allows me to extend the class definition. I can do this by implementing another partial class named the same:

public partial class Page : IPage
{
    IRoute IPage.Route
    {
        get { return this.Route; }
        set { this.Route = (Route)value; }
    }
}

 

At runtime, the compiler will combine both mine and the auto-generated Page class into one. Originally, my Page table had a one-to-one relationship with the Route table. I want the Route property on Page to return an IRoute though, so I've explicitly implemented this property from the IPage interface so that anyone programming against IPage sees an IRoute - but Linq to Sql, which works against the concrete Page type, will of course still see the concrete Route type. The same would be true for any one-to-many relationships; in the interface I would declare them as a generic IList<T>. EntitySet<T>, the type that Linq to Sql uses for collections, actually implements IList<T>, so it's just an implicit cast to get that working too.

But this only gets us halfway there. The autogenerated DataContext still exposes a Table<Page> type, when we really want a Table<IPage> type - or even better, the much more abstract IQueryable<T> type. What we need, is a pattern devised a long time ago...

The Repository Pattern

From Fowler, "conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them". From Evans, "the Repository retrieves the requested object, encapsulating the machinery of database queries and metadata mapping". That last quote is lifted from his book Domain Driven Design (p. 151), which he published back in 2004. What is funny, is that he goes on to say that "a Repository lifts a huge burden from the client, which can now talk to a simple, intention-revealing interface, and ask for what it needs in terms of the model. To support all this requires a lot of complex technical infrastructure". That first part is spot on. But the part about implementing the repository pattern being complex? I guess we've come a long, long way these last four years - C# 3.0 and Linq does away with all the complexity for us, so that all we have to do to implement a super-flexible Repository is defining something like the following interface:

public interface IDataContext, IDisposable
{
    /// <summary>
    /// Gets the repository for the given type of entities
    /// </summary>
    /// <typeparam name="T">The type of the entity</typeparam>
    /// <returns>The repository of the given type</returns>
    IQueryable<T> Repository<T>() where T : class, IEntity;
 
    /// <summary>
    /// Adds a new entity to the repository
    /// </summary>
    /// <typeparam name="T">The type of the entity</typeparam>
    /// <param name="item">The entity to add</param>
    void Insert<T>(T item) where T : class, IEntity;
 
    /// <summary>
    /// Deletes the specified entity from the repository
    /// </summary>
    /// <typeparam name="T">The type of the entity</typeparam>
    /// <param name="item">The entity to delete</param>
    void Delete<T>(T item) where T : class, IEntity;
 
    /// <summary>
    /// Commits the changes to the repository
    /// </summary>
    void Commit();
}

 

That's it! And implementing this interface for Linq to Sql is not much harder:

public class LinqToSqlContext : IDataContext
{
    private readonly DataContext _context;
 
    public static Dictionary<Type, Type> TableMaps = new Dictionary<Type, Type>();
 
    public LinqToSqlContext(DataContext context)
    {
        _context = context;
    }
 
    /// <summary>
    /// Gets the repository for the given type of entities
    /// </summary>
    /// <typeparam name="T">The type of the entity</typeparam>
    /// <returns>The repository of the given type</returns>
    public IQueryable<T> Repository<T>() where T : class, IEntity
    {
        ITable table = _context.GetTable(TableMaps[typeof(T)]);
        return table.Cast<T>();
    }
 
    /// <summary>
    /// Deletes the specified entity from the repository
    /// </summary>
    /// <typeparam name="T">The type of the entity</typeparam>
    /// <param name="item">The entity to delete</param>
    public void Delete<T>(T item) where T : class, IEntity
    {
        ITable table = _context.GetTable(TableMaps[typeof(T)]);
        table.DeleteOnSubmit(item);
    }
 
    /// <summary>
    /// Adds a new entity to the repository
    /// </summary>
    /// <typeparam name="T">The type of the entity</typeparam>
    /// <param name="item">The entity to add</param>
    public void Insert<T>(T item) where T : class, IEntity
    {
        ITable table = _context.GetTable(TableMaps[typeof(T)]);
        table.InsertOnSubmit(item);
    }
 
    /// <summary>
    /// Commits the changes for this unit of work to the repository
    /// </summary>
    public void Commit()
    {
        _context.SubmitChanges();
    }
 
    public void Dispose()
    {
        // we don't assume to manage the lifetime of the data 
        // context, so there's nothing to dispose
    }
}

 

The magic that lets us run queries against for example IPage, is in the Cast<T> extension method in System.Linq. By using it, it allows clients to ask the Repository<T> method for IPage, which then through the mapping configured in the static TableMaps dictionary (where at application startup I've added the mapping between IPage and Page) gets translated into a request for the Page table from the context, and then finally cast back to a IQueryable<IPage> before being returned to the caller, ready for querying against. The implementation-specific code I posted at the beginning of this article can now be thrown away in favour of the following more loosely coupled code:

var query = from pages in dataContext.Repository<IPage>() where pages.IsPublished select pages;
 
foreach (IPage page in query)
{
    // do something with page...
}

 

The Power of an Abstraction is it's Transparent Plugability

One clear win from doing things this way, is the transparent plugability that we achieve by hiding the DataContext behind our repository abstraction. For writing tests, this is invaluable. We can now implement a simple InMemoryDataContext that satisfies all the operations of the interface, allowing us to fake an actual database for testing purposes. The usage of Linq against the IQueryable<T> type means that any query in our application will then instead be executed in-memory instead of translated to SQL, completely transparent from the calling code. My InMemoryDataContext looks like this:

public class InMemoryDataContext : IDataContext
{
    private readonly List<object> _inMemoryDataStore = new List<object>();
 
    public IQueryable<T> Repository<T>() where T : class, IEntity
    {
        var query = from objects in _inMemoryDataStore
                    where typeof (T).IsAssignableFrom(objects.GetType())
                    select objects;
 
        return query.Select(o => (T)o).AsQueryable();
    }
 
    public void Insert<T>(T item) where T : class, IEntity
    {
        _inMemoryDataStore.Add(item);
    }
 
    public void Delete<T>(T item) where T : class, IEntity
    {
        _inMemoryDataStore.Remove(item);
    }
 
    public void Commit()
    {
        InvokeCompleted(EventArgs.Empty);
    }
 
    public event EventHandler Completed;
 
    private void InvokeCompleted(EventArgs e)
    {
        EventHandler completedHandler = Completed;
        if (completedHandler != null) completedHandler(this, e);
    }
}

 

Notice in particular that I've modified the Commit method to raise an event upon being called, so that tests which expect a Commit call can easily assert this. For example, I have a test to verify that when the title of a page is edited, the edited page gets committed to the draft repository (which is another great possibility of having the abstraction at hand - by injecting a special implementation of IDataContext when in page editing mode, I can make it so that changes done in the editor commit to a different storage location than the live data that site visitors see, until the user hits 'Publish'):

[TestClass]
public class When_SetTitle_action_executed
{
    const string route = "#";
    const string newTitle = "##";
    private Page page;
    private InMemoryDataContext context;
    private EditorController controller;
 
    [TestInitialize]
    public void Setup()
    {
        page = new Page {Route = new Route {Path = route}};
        context = new InMemoryDataContext();
        context.Insert(page);
 
        controller = new EditorController(context, MockHelpers.FakeTemplateRepository);
    }
 
    [TestMethod]
    public void New_title_gets_committed()
    {
        bool completed = false;
        context.Completed += (s,e) => completed = true;
 
        controller.SetTitle(route, newTitle);
 
        Assert.IsTrue(completed);
    }
    
// other tests omitted
}

 

And that's it for now. Hopefully this post makes some sense; much of what was written here comes fresh from my Visual Studio instance running in the background. If nothing else, I felt that writing this post helped clarify to myself what I needed to achieve, and that it does in fact seem like a good choice to make for my persistence strategy :)

Currently rated 4.9 by 21 people

  • Currently 4.857143/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Inversion of Control, ASP.NET MVC and Unit Testing

An entry about asp.net mvc | tdd | design patterns Publication date 18. April 2008 23:09

A couple of days ago, a new preview of the ASP.NET MVC framework was made available on Codeplex. It contains some very welcome changes that makes testing controllers much more enjoyable than before. You can read all about the changes over at Scott Guthries blog; in this post I'd like to show a quick demonstration of how we can use the inversion of control pattern to streamline writing testable controllers. If you're not familiar with the concepts of IOC, it can be explained as a design pattern which comes in several flavours, all of which aim to help you write more loosely coupled code. To get started, "Inversion of Control and the Dependency Injection pattern" by Martin Fowler is a must-read, and Jimmy Bogard has a great series of posts explaining the pattern and the principles from which it came to be.

With that out of the way, let's get on with our demonstration. Let's assume that we're tasked with building a blog engine. One of the things we'll need, is an action that can display a single blog post. Good TDD citizens that we are, let's start off by writing a test first:

[TestMethod]
public void ShowPost()
{
    const string title = "Some Post Title";
    const string urlTitle = "Some-Post-Title";
 
    // set up mocks
    Mock<IPost> article = new Mock<IPost>();
    Mock<IPostRepository> repository = new Mock<IPostRepository>();
    repository.Expect(r => r.GetPost(title)).Returns(article.Object);
 
    // excersize method under test
    PostController controller = new PostController(repository.Object);
    RenderViewResult result = controller.ShowPost(urlTitle) as RenderViewResult;
 
    // verify result of test
    Assert.IsNotNull(result);
    Assert.AreSame(article.Object, result.ViewData);
    Assert.AreEqual("Post", result.ViewName);
}

 

Okay, so when writing the test I was forced to make some decisions on the architecture of my blog engine. The first thing I realized, was that I'd need some entity to represent a blog post. For this, I created an interface IPost. Then, I realized I'd need some way of locating a post from the database, so I created the IPostRepository interface and gave it a single method; GetPost. This method takes the title of the post as its only argument, because I knew that I'd want the URL's in my blog to look something like http://myblog.com/Posts/Some-Post-Title.

Digression: The Importance of Testing in Isolation

The great thing up until now, is that I've not written a single line of actual code - all I've done is define a few interfaces and basically draw up the blueprints of the application. This is important with respect to test-driven development; here I'm writing a test to help me implement the ShowPost action method on the PostController class, but to implement that method I come across dependencies to other classes (which might not even be implemented yet, as is the case here), and I need to take them out of the equation so that I can write my test without it depending on their implementations (and inherently, their correctness). Notice that I've used a mocking library (Moq) to help me accomplish this. Testing in isolation is one of the most important aspects of writing useful unit tests; I cannot stress that enough. If you don't isolate your tests and you introduce a bug somewhere, then not only the test that verifies that particular code path will fail, but loads of tests all over the place will fail because they too depend on the code containing the bug. Not only will it be much harder to track down the offending line(s) of code, but seeing a sea of tests go red doesn't exactly do wonders for your motivation either. Unit testing should be like playing reverse Domino; the goal is to not knock over any other pieces if one should tip over.

Back on Track...

Okay, digression aside. So, if you've played about with the previous beta releases of ASP.NET MVC, you probably noticed that our controller action method now has a return value - an ActionResult object, which we've cast to a RenderViewResult object. This is one of the changes that have been done in the new version, which drastically simplifies unit testing. If you've tried to write tests for controllers previously, you may also notice the distinct lack of any code in my test to deal with mocking the Http context and all that stuff - we don't need to anymore (Woo!). I can just capture the return value of calling the action method and use it to assert that the action set the right view data and requested the right view, and so forth.

Running the test now should make it fail - we've yet to actually implement the ShowPost method on the PostController. That's easy to remedy, however:

public class PostController : Controller
{
    private readonly IPostRepository _repository;
 
    public PostController(IPostRepository repository)
    {
        _repository = repository;
    }
 
    public ActionResult ShowPost(string title)
    {
        title = title.Replace("-", " ");
 
        IPost post = _repository.GetArticle(title);
        return RenderView("Post", post);
    }
}

 

Resolving Dependencies

For our test, we manually injected the IPostRepository dependency into the PostController - but that won't do when we actually browse to the URL routed to the action; out of the box, ASP.NET MVC won't know how to create an instance of the PostController because its constructor is not parameterless. That's where an IOC container comes into the picture - it'll let us register all the dependencies our application requires in one single place, making it easy to manage and maintain them, and then it'll take care of figuring out which dependencies goes where when instantiating objects. As I mentioned previously, I really dig Autofac, so I'll be demonstrating how we'd do things using it.

Autofac with ASP.NET MVC

There's already a page in the Autofac wiki which goes through this, so I'll just quickly skim through it here for completeness. The first thing we'll need to do, is register a couple of Http modules in the web.config file, which Autofac needs to do its magic:

<httpModules>
  <add name="ContainerDisposal" type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"/>
  <add name="PropertyInjection" type="Autofac.Integration.Web.PropertyInjectionModule, Autofac.Integration.Web"/>

 

That done, we'll jump to the Global.asax file. Autofac comes with an already ready ASP.NET MVC integration module, so all we need to do is to hook things up. That means our Global.asax file will look like this:

public class GlobalApplication : HttpApplication, IContainerProviderAccessor
{
    static IContainerProvider _containerProvider;
 
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute(
            "Article",
            "Articles/{*title}",
            new { controller = "Article", action = "ShowPost" },
            new { title = @"[^\.]*" }
        );
    }
 
    protected void Application_Start()
    {
        // when the application starts, we need to build the container and register all
        // the dependencies that we want it to manage for us
        var builder = new ContainerBuilder();
 
        // we register the implementation of our IPostRepository as a singleton
        builder.Register<SqlPostRepository>().As<IPostRepository>().SingletonScoped();
 
        // and then we'll use the AutofacControllerModule to register all the controllers it finds in the given assembly
        builder.RegisterModule(new AutofacControllerModule(Assembly.GetExecutingAssembly()));
 
        // finally we build the container...
        _containerProvider = new ContainerProvider(builder.Build());
 
        // ...and notify ASP.NET MVC that it should use Autofacs own controller factory to instantiate controllers,
        // so that Autofac can resolve any dependencies the controllers need
        ControllerBuilder.Current.SetControllerFactory(new AutofacControllerFactory(_containerProvider));
 
        RegisterRoutes(RouteTable.Routes);
    }
 
    public IContainerProvider ContainerProvider
    {
        get { return _containerProvider; }
    }
}

 

The interesting part is the Application_Start method. Here, we instantiate the container and register all the dependencies (well, we just have the one, IPostRepository, but you get the idea). We also register all the controllers, because we want the container to be in charge of instantiating these, so that it can resolve any dependencies they rely on. To make this work, we tell ASP.NET MVC to use the Autofac controller factory instead of its own. Now, whenever a request comes in, Autofac will be in charge of instantiating the controller, and it will scan the constructor and look up any dependencies that are required and inject them accordingly. And that's it; we have a controller that is a breeze to decouple from its dependencies, making it easily testable in isolation, and with an IOC container in place all the complexity of loose coupling the dependencies is taken off our hands. Oh, how I wish all the code I worked on was like this (damn you, legacy code! :p).

Currently rated 3.5 by 8 people

  • Currently 3.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Composite Oriented Programming

An entry about arcitechture | design patterns Publication date 27. February 2008 18:18

I've written a series of post on AOP lately (here, here and here), and in the last part I promised to tackle mixins and introductions in a future post. When I was doing my research for just that, I came cross a Java framework (just humor me :p) called Qi4j (that's 'chee for jay'), written by Swedish Richard Öberg, pioneering the idea of Composite Oriented Programming, which instantly put a spell on me. Essentially, it takes the concepts from Aspect Oriented Programming to the extreme, and for the past week I’ve dug into it with a passion. This post is the first fruits of my labor.

OOP is Not Object Oriented!

One of the things that Richard Öberg argues, is that OOP is not really object oriented at all, but rather class oriented. As the Qi4j website proclaims, "class is the first class citizen that objects are derived from. Not objects being the first-class citizen to which one or many classes are assigned". Composite oriented programming (COP) then, tries to work around this limitation by building on a set of core principles; that behavior depends on context, that decoupling is a virtue, and that business rules matter more. For a short and abstract explanation of COP, see this page. In the rest of this post I'll try and explain some of its easily graspable benefits through a set of code examples, and then in a future post we'll look at how I've morphed the AOP framework I started developing in the previous posts in this series into a lightweight COP framework that can actually make it compile and run.

Lead by Example

Lets pause for a short aside: obviously the examples presented here are going to be architectured beyond any rational sense, but the interesting part lies in seeing the bigger picture; imagine the principles presented here applied on a much larger scale and I'm sure you can see the benefits quite clearly when we reach the end.

Imagine that we have a class Division, which knows how to divide one number by another:

public class Division
{
    public Int64 Dividend { get; set; }
 
    private long _divisor = 1;
 
    public Int64 Divisor
    {
        get { return _divisor; }
        set 
        {
            if(value == 0)
            {
                throw new ArgumentException("Cannot set the divisor to 0; division by 0 is not allowed.");
            }
 
            _divisor = value; 
        }
    }
 
    public Int64 Calculate()
    {
        Trace.WriteLine("Calculating the division of " + this.Dividend + " by " + this.Divisor);
 
        Int64 result = this.Dividend/this.Divisor;
 
        Trace.WriteLine("Returning result: " + result);
 
        return result;
    }
}

Consider the code presented above. Do you like it? If you've followed the discussion on AOP in the previous posts, then you should immediately be able to identify that there are several aspects tangled together in the above class. We've got data storage (the Dividend and Divisor properties), data validation (the argument check on the Divisor setter), business logic (the actual calculation in the Calculate method) and diagnostics (the Trace calls), all intertwined. To what extent is this class reusable if I wanted to implement addition, subtraction or multiplication calculations? Not very, at least not unless we refactored it. We could make the Calculate method and the properties virtual, and thus use inheritance to modify the logic of the calculation - and since this is a tiny example, it would probably look OK. But again, think bigger - how would this apply to a huge API? It would easily become quite difficult to manage as things got more and more complex.

Design by Composition

With a COP framework, we can implement each aspect as a separate object and then treat them as mixins which blend together into a meaningful composite. Sounds confusing? Lets refactor the above example using an as of yet imaginary COP framework for .NET (which I’m currently developing and will post the source code for in a follow-up post), and it'll all make sense (hopefully!).

Above, we identified the four different aspects in the Division class - so let's implement each of them. First, we have the data storage:

public interface ICalculationDataAspect // aspect contract
{
    long Number1 { get; set; }
    long Number2 { get; set; }
}
 
public class CalculationDataAspect : ICalculationDataAspect // aspect implementation
{
    public long Number1 { get; set; }
    public long Number2 { get; set; }
}

In this example, the data storage is super easy – we just provide a set of properties (using the C# 3.0 automatic properties notation) that can hold the values in-memory. The second aspect we found, was the business logic – the actual calculation:

public interface ICalculationLogicAspect
{
    long Calculate();
}
 
public class DivisionLogicAspect : ICalculationLogicAspect
{
    [AspectRef] ICalculationDataAspect _data;
 
    public long Calculate()
    {
        return _data.Number1 / _data.Number2;
    }
}

Here we follow the same structure again, by defining the aspect as an interface and providing an implementation of it. In order to perform the calculation however, we need access to the data storage aspect so that we can read out the numbers we should perform the calculation on. Using attributes, we can tell the COP framework that we require this reference, and it will provide it for us at runtime using some dependency injection trickery behind the scenes. It is important to notice that we’ve now placed a constraint on any possible composition of these aspects – the DivisionLogicAspect now requires an ICalculationDataAspect to be present in any composition it is part of (our COP framework will be able to validate such constraints, and tell us up front should we break any). It is still loosely coupled however, because we only hold a constraint on the contract of that aspect, not any specific implementation of it. We'll see the benefit of that distinction later.

The third aspect we have, is validation. We want to ensure that the divisor is never set to 0, because trying to divide by zero is not a pleasant experience. Validation is a type of advice, which was introduced at length earlier in my AOP series. We've seen it implemented using the IAdvice interface of my AOP framework, allowing us to dynamically hook up to a method invocation. However, the advice we’re implementing here is specific to the data aspect, so with our COP framework we can define it as concern for that particular aspect, which gives us a much nicer implementation than an AOP framework could - in particular because of its type safety. Just look at this:

public abstract class DivisionValidationConcern : ICalculationDataAspect
{
    [ConcernFor] protected ICalculationDataAspect _proceed;
 
    public abstract long Number1 { get; set; }
 
    public long Number2
    {
        get { return _proceed.Number2; }
        set
        {
            if (value == 0)
            {
                throw new ArgumentException("Cannot set the Divisor to 0 - division by zero not allowed.");
            }
 
            _proceed.Number2 = value; // here, we tell the framework to proceed with the call to the *real* Number2 property
        }
    }
}

I just love that, it's so friggin' elegant ;). Remember that an advice is allowed to control the actual method invocation by telling the target when to proceed – we’re doing the exact same thing above, only instead of dealing with a generic method invocation we're actually using the interface of the aspect we're advising to control the specific invocation directly. In our validation, we validate the value passed into the Divisor setter, and if we find it valid then we tell the target (represented by a field annotated with an attribute which tells the COP framework to inject the reference into it for us, much like we did with aspects earlier) to proceed with the invocation; otherwise we throw an exception. This particular concern is abstract, because we only wanted to advise a subset of the methods in the interface. That's merely a convenience offered us by the framework - under the covers it will automatically complete our implementation of the members we left abstract.

Only one aspect remains now, and that is the logging:

public class LoggingAdvice : IAdvice
{
    public object Execute(AdviceTarget target)
    {
        Trace.WriteLine("Invoking method " + target.TargetInfo.Name + " on " + target.TargetInfo.DeclaringType.FullName);
 
        object retValue;
 
        try
        {
            retValue = target.Proceed();
        }
        catch(Exception ex)
        {
            Trace.WriteLine("Method threw exception: " + ex.Message);
            throw;
        }
 
        Trace.WriteLine("Method returned " + retValue);
 
        return retValue;
    }
}

We’ve implement it as a regular advice, like we've seen earlier in AOP, because it lends itself to much wider reuse than the validation concern did.

Having defined all our aspects separately, it is now time to put them back together again into something that can actually do something. We call this the composite, and it is defined as follows:

[Mixin(typeof(ICalculationDataAspect), typeof(CalculationDataAspect))]       
[Mixin(typeof(ICalculationLogicAspect), typeof(DivisionLogicAspect))]
[Concern(typeof(DivisionValidationConcern))]
[Concern(typeof(LoggingAdvice))]
public interface IDivision : ICalculationDataAspect, ICalculationLogicAspect 
{ }

Basically, we’ve just defined the implementation of an interface IDivision as a composition of the data and logic aspects, and sprinkled it with the two concerns (the validation concern and the logging advice). We can now use it to perform divisions:

IDivision division = Composer.Compose<IDivision>().Instantiate();
division.Number1 = 10;
division.Number2 = 2;
 
Int64 sum = division.Calculate();

That’s pretty cool, no? Take a moment to just think about what doors this opens. To what extent do you think our code is reusable now, if we wanted to implement addition, subtraction and so forth? That’s right – all we’d need to do is substitute the implementation of the calculation aspect with one that performs the required calculation instead of division, and we're done. Let’s do subtraction, for example:

public class SubtractionLogicAspect : ICalculationLogicAspect
{
    [AspectRef] ICalculationDataAspect _data;
 
    public long Calculate()
    {
        return _data.Number1 - _data.Number2;
    }
}

That’s it! The rest we can reuse as is, building a new composite:

[Mixin(typeof(ICalculationDataAspect), typeof(CalculationDataAspect))]
[Mixin(typeof(ICalculationLogicAspect), typeof(SubtractionLogicAspect))]
[Pointcut(typeof(LoggingAdvice))]
public interface ISubtraction : ICalculationDataAspect, ICalculationLogicAspect
{ }

Notice that we just left out the validation concern in this composite, as it is no longer needed. What if we wanted our subtraction to only ever return positive numbers? Easy! We’ll just implement an absolute number concern:

public class AbsoluteNumberConcern : ICalculationLogicAspect
{
    [ConcernFor] protected ICalculationLogicAspect _proceed;
 
    public long Calculate()
    {
        long result = _proceed.Calculate();
 
        return Math.Abs(result);
    }
}

And then update the composition to include it:

[Mixin(typeof(ICalculationDataAspect), typeof(CalculationDataAspect))]
[Mixin(typeof(ICalculationLogicAspect), typeof(SubtractionLogicAspect))]
[Concern(typeof(AbsoluteNumberConcern))]
[Pointcut(typeof(LoggingAdvice))]
public interface ISubtraction : ICalculationDataAspect, ICalculationLogicAspect
{ }

To Be Continued…

I hope this post has whet your appetite for more on this subject, as I will certainly pursue it further in future posts. I’ve already implemented a prototype framework that supports the above examples, which builds on my previously posted AOP framework, and I’ll post the source code for that soon. If you want to dig deeper right now (and don’t mind a bit of Java), then I suggest you head over to the Qi4j website and poke about there. Richard Öbergs blog also provides great insight.

Currently rated 5.0 by 3 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.

Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS