Archive

I’ve been lucky enough to be selected as a speaker for NYC Code Camp 2011 on February 19th. You’ll find me in the Radio City room at 9h15. I'll deliver my introduction talk Produce Cleaner Code with Aspect-Oriented Programming.

I’ll be in Manhattan from Wednesday evening till Sunday afternoon. If you don’t attend the code camp and want to meet up, please contact me by email (gael@sharpcrafters.com) or by phone at +420 775011188.

It’s the first time I’ll cross the Atlantic so I feel a bit like Tintin in America. I’ve been in the land of Soviets and Congo (although I lived Congo before visiting Russia), so I’m pretty much respecting the order of the series.


Next stop: the Cigars of Pharaoh?

-gael

imageVSone kicks-off February 16th in Munich, Germany and will feature two days of presentations on Microsoft technologies including Silverlight, Life Cycle Management Application, SQL Server and data modeling, Azure, Web development, UI and devices, architecture and core programming, etc.

We recently caught up with Johannes Hoppe, who will speak at VSone on February 17th, invited him for a chat about his session on Aspect-Oriented Programming, and convinced him to give our German readers a sneak preview.

Britt: Why did you choose to speak about Aspect-Oriented Programming at VSone?

Johannes: The Clean Code movement has really taken off in Germany in the past few years and writing pragmatic clean code is something I’m passionate about. I shifted to aspect-oriented programming on some projects recently and have been amazed at the number of lines of code it has saved me. I wanted to share these insights with VSone attendees.

Britt: Why should VSone attendees care about AOP?

Johannes: For the same reason they care about clean code. AOP is an effective way to produce cleaner code and I believe it deserves to be used by more developers. Developers attend events like VSone because they’re looking for quick wins – learning things that they can implement right away – and my presentation is perfect for developers who want a quick introduction to Aspect-Oriented Programming. During the presentation I’ll show some production-ready aspects that I’ve prepared and make them available to attendees for download so they can start to use them right away in their own code.

Britt: What was your first experience with AOP?

Johannes: Early last year I was working on a project that had a tight deadline. My team had done unit tests and they all showed green but we still felt something wasn’t quite right. My boss told us to do a soft release and we sent 300 visitors (from a mailing list) to the website and the webserver nearly exploded.

We smartly decided not to go live with the project and instead looked at where the peaks were coming from. That was the first time I used AOP. We made a summary of the method runtimes and I used an aspect to log the method execution times to find the problem – a mistake on one of the most frequently used methods which made everything super slow – and later used a caching aspect to fix it. I’ve been addicted ever since.

Britt: Have you ever lectured about AOP to your students?

Johannes: No, not yet! My previous lectures have been about other topics but I’m hoping to introduce it in an upcoming “Software Architecture and Development” course. In the meantime my students are using “AOP- flavored” code without knowing it – for example the ASP.NET MVC HandleError Attribute and the Dependency Attribute from Unity. I like it when aspects are unobtrusive.

Britt: What will VSone attendees see in your presentation that’s not shown in your sneak preview?

Johannes: In addition to the introduction to AOP and showing how to make messy code clean again using common AOP patterns, attendees will see a live example of a logging aspect – I’ll show how easy it is to apply – followed by validation and caching aspects in real world scenarios. If there is time, I’d love to show my StackOverflow aspectthat finds unwanted recursion, including a real world disaster story of when it showed up in my life.

Britt: Where can our readers learn more about you?

My blog is a good start: http://blog.johanneshoppe.de/. I’m planning to publish some articles in print magazines soon, too. Readers can also go to my ADO.NET Unit Testable Repository Generator: http://repositorygenerator.codeplex.com/ which is something I’m quite proud of.

Britt: Which technologies interest you most and why?

Johannes: My daily work covers a lot of Microsoft technologies. At the moment I’m concentrated on ASP.NET MVC – the best MS platform for building websites, EXT.NET framework – a great tool for building RIA apps really fast, and Windows Phone 7 development. Microsoft gave me two Windows Phone 7s for ”free,” one as a finalist in the Imagine Cup and the other one I got for my Microsoft Student Partner Program efforts. Now I have to develop something for it.

Britt: Which sessions are you planning to attend at VSone?

There are so many good sessions at the same time it’s hard to decide which to attend. I will definitely go to Rouven Haban’s session “ASP.NET MVC in Practice.” In which he will talk about one of his recent projects of which I’m very interested. Thankfully his session is an hour before mine.

Britt: What’s this I hear about you and footbagging?

I was VERY into footbagging a few years ago and loved it so much that I built a footbag online shop http://www.footbag-shop.de/and later realized their potential as marketing vehicles http://www.promotion-footbags.de/. Footbagging is still one of my favorite outdoor games to play during breaks. Whenever I find some time, I like to make that little ball dance with my feet. I can’t wait for spring, it’s the best time for footbagging really!

Britt: You had me at “very.”

imageJohannes is a lecturer at SRH University Heidelberg and is very involved in the Microsoft Student Partner program on campus – running workshops and mentoring students. He has been working independently for over 10 years, is crazy about web design, and currently works on ASP.NET MVC and PHP projects. When he’s not working on projects or footbagging, Johannes keeps a blog about his adventures in lecturing at http://blog.johanneshoppe.de/.

Source code used in these blog posts is available on GitHub

How many times have you written something like this:

private IProductRepository _productRepository;
private IProductRepository ProductRepository
{
    get
    {
        if(_productRepository == null)
        {
            _productRepository = new ProductRepository();
        }
        return _productRepository;
    }
}

This is a piece of code that you might write dozens or more times to be able to use a repository to return some data to use in your application. If you're in a hurry, it's a quick way to get something that works, and also an easy way to get some lazy loading in place so that the repository doesn't instantiate until you need it to. Unfortunately, this piece of code incurs technical debt. And the more you use this boilerplate elsewhere in your code, the more technical debt you incur.

There are two things in this code that are incurring the debt: hardwired dependencies and boilerplate code.

Generally, I prefer to use an IoC container to wire up these sort of dependencies for me, but that isn't always possible or easy to do, especially when I'm programming within a framework that doesn't have dependency injection in mind (WinForms/WebForms, etc). It's not impossible to do DI on those frameworks without PostSharp, but it's certainly a lot more work.

While the property itself is of type IProductRepository, the getter of that property is still hard-wired to ProductRepository. If you need to change "new ProductRepository()" to "new RevisedProductRepository()" or even "new ProductRepository(2011)", you must go through each instance of your boilerplate and update the code. Sure, you could try a find & replace, but each other programmer on your team could be making changes, tweaks, adjustments, and now a find & replace might break something, or might not even work. Wouldn't it be better to have those dependencies configured in one central place, instead of scattered throughout your entire app? Using a service locator from an IoC framework, for instance, you could get this:

private IProductRepository _productRepository;
private IProductRepository ProductRepository
{
    get
    {
        if(_productRepository == null)
        {
            _productRepository = ObjectFactory.GetInstance<IProductRepository>();
        }
        return _productRepository;
    }
}

And now the ObjectFactory will take care of the instantiations. If you want to plug in a new concrete implementation, wrap the existing implementation, add constructor parameters, etc, now you can do it all in once place. (Note that "ObjectFactory" is a static class in StructureMap , but you could use any IoC container that you like). Now the code looks much better, and the development team doesn't have to worry about the implementation: only the interface. It's still a true dependency inversion, because now the class only depends on the interface, not the implementation.

The code is now much cleaner, but we still have a bunch of null checking and lazy loading scattered all over the app. If you decide to change to a different IoC container, you still have to make changes throughout your app. And if you get to the point where the simple null-checking strategy isn't good enough, then you have to change that everywhere too. Let's use PostSharp to centralize this logic, so you can save time and DRY up your code while you're at it.

[LoadDependency] private IProductRepository _productRepository;

[Serializable]
public sealed class LoadDependencyAttribute : LocationInterceptionAspect
{
    public override void OnGetValue(LocationInterceptionArgs args)
    {
        args.ProceedGetValue(); // fetches the field and populates the args.Value
        if (args.Value == null)
        {
            var locationType = args.Location.LocationType;
            var instantiation = ObjectFactory.GetInstance(locationType);

            if (instantiation != null)
            {
                args.SetNewValue(instantiation);
            }
            args.ProceedGetValue();
        }
    }
}

Now you have a very declarative way of using dependencies. You simply tag any field with the "LoadDependency" attribute, and it will be instantiated by your IoC container the first time you use it. You save yourself from having to write the same boilerplate properties over and over again, and the null-checking/lazy loading itself is now centralized into a single class (LoadDependencyAttribute).

With just a simple PostSharp aspect, we've compressed a 12-line lazy-loading property into a one-line field, with no hard-wired dependencies or boilerplate code. We've removed a lot of pointless repetition from the code (DRY ). We've replaced hard-wired dependencies with pure interfaces (DIP ). We've moved the lazy-loading into its own class, and dependency resolution into its own class (SRP ). Since PostSharp won't try to use the service locator if the field isn't null, you can easily use constructor injection as part of your testing instead of letting PostSharp load the real dependency. Our app is on the fast track to being a maintainable, easy to configure, and easy to test masterpiece.

This is a very helpful, and very simple example of how to use PostSharp to make your life easier.

Now suppose that the dependency mappings (like IProductRepository <-> ProductRepository in the above example) is already known at compile time. That is, the dependency will not change during runtime. In this case, you don't need to use a service locator at all. You can instead override the CompileTimeInitialize method in LocationInterceptionAspect to resolve the dependency at compile time (hence the name), and just store the type as a field. Then, at run time, you can use Activator.CreateInstance to do the instantiation.

[Serializable]
public sealed class LoadDependencyAttribute : LocationInterceptionAspect
{
    private Type _type;

    public override bool CompileTimeValidate(PostSharp.Reflection.LocationInfo locationInfo)
    {
        _type = DependencyMap.GetConcreteType(locationInfo.LocationType);
        if(_type == null)
        {
            Message.Write(SeverityType.Error, "002",
					"A concrete type was not found for {0}.{1}",
					locationInfo.DeclaringType, locationInfo.Name);
            return false;
        }
        return true;
    }

    public override void OnGetValue(LocationInterceptionArgs args)
    {
        args.ProceedGetValue();
        if (args.Value == null)
        {
            form.LogListBox.Items.Add("Instantiating UserService");
            args.SetNewValue(Activator.CreateInstance(_type));
            args.ProceedGetValue();
        }
    }
}

If there isn't a type configured, then you will get a build time error instead of a runtime error. You are hopefully starting to see that PostSharp can be a very powerful tool. I'm not too keen on using this method to totally replace a runtime service locator, but I can certainly see where it would be useful in some select circumstances.

Another way to improve either of the above aspects is to do a compile-time check to validate that the aspect is being used correctly. For instance, using the LoadDependency attribute usually doesn't make sense if you apply it to a field that isn't an interface. Indeed, this would be a bad design, as it would make our dependencies hard coded again! So let's put some code into place to prevent this sort of code from even getting compiled. Just add one more check to the CompileTimeValidate method:

public override bool CompileTimeValidate(PostSharp.Reflection.LocationInfo locationInfo)
{
    if(!locationInfo.LocationType.IsInterface)
    {
        Message.Write(SeverityType.Error, "001",
			"LoadDependency can only be used on Interfaces in {0}.{1}",
			locationInfo.DeclaringType, locationInfo.Name);
        return false;
    }

    _type = DependencyMap.GetConcreteType(locationInfo.LocationType);
    if(_type == null)
    {
        Message.Write(SeverityType.Error, "002",
			"A concrete type was not found for {0}.{1}",
			locationInfo.DeclaringType, locationInfo.Name);
        return false;
    }
    return true;
}

Go ahead and put LoadDependency on a non-interface field, compile, and this is what you'll see:

Visual Studio build error

And you'd get a similar message if you forgot to put a interface<->concrete mapping in the DependencyMap class too. This is such a great feature, because if you make a mistake, you will fail much faster in your testing, get a clear message of what exactly went wrong, and ultimately save a lot of time and frustration. Make sure to put as much information as you can in the error message, to make the error easy to find in the code, since you won't have line numbers to fall back on.

With just a simple aspect, we've turned our hard-coded dependencies and repetitive boilerplate code into a maintainable, testable, easy-to-read app that follows SOLID principles. More importantly, you will save a lot of time, not just in the development and testing phases of your project, but also in the (usually much longer) maintanence phase.

Matthew D. Groves is a software development engineer with Telligent, and blogs at mgroves.com.