Showing posts with label Aspect Oriented Programming. Show all posts
Showing posts with label Aspect Oriented Programming. Show all posts

Thursday, September 3, 2009

Head First Design Patterns

Head First Design PatternsI read Head First Design Patterns about a year ago and it changed my life. Now, I know that a lot of non-programmers read this blog and I'm sure you must be thinking, "how can a book, especially one like that, possibly change your life?"

Well, it made my code much cleaner, much more flexible, and much easier to write. That's why I decided to make this the first book review on this blog. First of all, I'm a pretty big fan of the Head First style. I like most of the jokes and intentional thought provoking. It's a clever way to help people understand and remember what they're learning. Admittedly, sometimes it goes a little overboard, but I'd rather it go a little overboard than be a dry read. I read almost the whole book on a road trip from Atlanta to Orlando.

The book sets out to give the reader an understanding of what a design pattern is and what it's good for. A design pattern is a template for solving commonly occurring problems in software design. Head First Design Patterns discusses the details of about 15. You'll be surprised how many of these patterns you've seen before (and may have even written before). One of the big benefits you get out of this book is a common language to describe the patterns in your code. Next time you're doing a code review, you'll find yourself saying things like, "this is just a singleton" and your reviewer will understand what you're trying to accomplish without discussing the implementation details.

After reading this book, I've noticed more and more patterns:

The decorator pattern that you see throughout the .net framework. There are a lot of classes that take a stream and return a stream. Some read, some write, some encrypt — all of them are decorators.

The proxy pattern controls access to other objects. I wrote a blog post back in December of 2008 where I used the proxy pattern to write to multiple TextWriters.

The singleton pattern ensures that a class has only one instance and has a global point of access. It bears noting that there are a lot of programmers who have criticized the singleton to which the singleton replied in a public statement last year, "you can kiss my ass." It is true that the singleton can come back to bite you if you use it incorrectly; the singleton is the right tool for the job it has. Head First Design Patterns helps you understand what exactly that job is.

The template method pattern popped up the other day when I was looking at some PostSharp aspects. If you use the OnMethodInvocationAspect like I did with my memoizer, PostSharp will produce something very similar to a template method. Obviously, PostSharp isn't creating a base class and then overriding the template method, but it is allowing you to control the flow of the method without having knowledge of the method implementation.

The factory method and abstract factory patterns are also quite common and are well described in Head First Design Patterns. People use these patterns all the time. I've seen many data access layer implementations where a factory method loads a particular data access provider based on configuration options. You can achieve the same results with inversion of control containers like Ninject and autofac, but sometimes you just need a quick factory.

Almost every review I've seen of Head First Design Patterns has been positive; however, every once in a while you find a detractor like Jeff Atwood in his blog post from 2005. I think Jeff is probably a good guy and a good coder; he's just contrary and cynical. I know that being contrary and cynical doesn't negate your point, but it is a bit like crying wolf. I'm not going to address his argument in this post (because I could dedicate an entire post to the argument if I thought it'd do any good), but I think you should read it because he does have one some valid points.

Unneeded complexity is bad. I wouldn't say that design patterns should be eschewed altogether, but you should use the right pattern for the right problem. Reading this book should teach you to identify patterns yourself. What are some common problems you run into in your field? Can you think of a pattern for addressing these problems?

You have to learn to abstract your knowledge and apply it practically. Don't just decide that patterns are bad and start knocking books because the graphic on the cover has been reused. A pattern doesn't have to be necessary to be valuable. When the pattern provides maintainability, readability, testability, or simplicity then use the pattern; that's what it's there for. The pattern is just another tool in your tool belt.

I very seldom recommend you throw a specialized tool away just because you don't need it all the time. Buy (or borrow) Head First Design Patterns and focus on learning how to recognize and solve common problems. You won't regret it.

You can get Head First Design Patterns from Amazon.com for a great price.

Wednesday, March 11, 2009

Validate Parameters Using Attributes and PostSharp

I've been learning a lot about C# 4.0 lately and I have been very intrigued by the design by contract capabilities that will be added with the Microsoft Research Code Contracts project. One feature I'm particularly excited about is the static validation.

I've been working on a project which is little more than an abstract class and a bunch of test cases to verify that the outsourced implementers of this class make appropriate parameter validation on their overridden methods. I thought, "man, it sure would be nice if I could just put a code contract on my abstract class and then I wouldn't have to write all of these annoying unit tests."

Well, I just couldn't wait, so again I leveraged the pre-compiler flexibility of PostSharp and AoP concepts to simplify things a little (at least until code contracts are widely supported).

The first thing I did was define the contract for my parameter validation attributes:
[AttributeUsage(AttributeTargets.Parameter)]
public abstract class ParameterAttribute : Attribute
{
public abstract void CheckParameter(ParameterInfo parameter, object value);
}
Then, I wrote a method attribute with a method boundary aspect to process the parameter attributes:
[Serializable]
public class HasParameterAttributes : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionEventArgs eventArgs)
{
ParameterInfo[] pis = eventArgs.Method.GetParameters();
Object[] args = eventArgs.GetReadOnlyArgumentArray();

for (int i = 0; i < pis.Length; i++)
foreach (ParameterAttribute pa in pis[i].GetAttributes<ParameterAttribute>())
pa.CheckParameter(pis[i], args[i]);

base.OnEntry(eventArgs);
}
}
The version I wrote in honor of my friend Sir Nathan Rigsby is called CanHazParameterAttributes.

The HasParameterAttributes method attribute implementation uses an extension method I wrote to get a specific type of attributes from the PropertyInfo objects. You can find it in the article entitled: Extension Method to Get Custom Attributes with Reflection

I wrote two basic parameter validators to test the system:
public class NotNull : ParameterAttribute
{
public string Message { get; set; }
public override void CheckParameter(ParameterInfo parameter, object value)
{
if (value == null)
throw new ArgumentNullException(parameter.Name, Message);
}
}

public class NotEmpty : ParameterAttribute
{
public string Message { get; set; }

public override void CheckParameter(ParameterInfo parameter, object value)
{
if (value != null && value.ToString().Length == 0)
throw new ArgumentException(Message, parameter.Name);
}
}
The test I wrote does not execute like you would expect a unit test to execute. That is because I didn't have a lot of time to spend on this so I was too lazy to specify which test cases expect exceptions and which don't. If you run these test cases, you'll see that the ones which throw exceptions fail and the ones which don't throw exceptions pass. They perform as designed. Here's my NUnit test:
[TestFixture]
public class Tests
{
[Test, Combinatorial]
[HasParameterAttributes]
public void TestNotNull
([NotNull, Values(null, "", "Lulu")] string param1,
[NotEmpty, Values(null, "", "Lulu", 0)] object param2)
{ }
}

Thursday, February 19, 2009

Memoizer Attribute Using PostSharp

I was doing a lot of research yesterday and I came across the memoization technique. I've written a cache proxy to provide lazy loading and event driven refreshes as well as to provide valid durations and several other features. I still like the cache proxy, but there could be times where that's just overkill and a little bit of caching will go a long way.

My co-worker (Jamus) and I were talking about memoization in Ruby on Rails and the implementation is so clean. Basically, it replaces the original method with a call to the memoizer which checks for a cached value which it either returns or replaces. I wanted something like this in C# (seeing as how I am a C# developer).

The blog I was reading that introduced me to the memoizer had a generic memoization method that didn't work, but with a little tweaking, it did just fine. You basically passed your method call through this generic method and it would handle first checking for your cached value before passing the call through to your original method.

The problem was, what if you had a recursive method? I was playing around with a factorial method (of course) that looked like this:
static int factorial(int n)
{
return n < 2 ? 1 : n * factorial(n - 1);
}

// test cases
//factorial(7);
//factorial(9);
//factorial(9);

The first test made 7 iterations through the factorial method, the second 9, and the third 0. I thought about it and it seemed like I'd be better off if I made each call to the memoizer, rather than the original method. That way, my first test would make 7 iterations, my second test 2, and the third test 0. The problem was, with the generic memoizer method, my factorial method would thus have to be aware of the memoizer and I didn't want that.

That's when Jamus introduced me to PostSharp. PostSharp is a library that modifies your code at compile time providing Aspect Oriented Programming capabilities to .NET. This was almost exactly what I was looking for . . . a way to cleanly separate the concerns of my application from the memoization concerns. PostSharp allowed me to take the memoization aspect out of the implementation of my methods and put them nicely into a method attribute. This is just a first version proof of concept so I haven't optimized it much, but I think the idea has a great deal of potential, so here it is:
    public static class Memoizer
{
// private field to store memos
private static Dictionary<string, object> memos = new Dictionary<string, object>();

// PostSharp needs this to be serializable
[Serializable]
public class Memoized : OnMethodInvocationAspect
{
// intercept the method invocation
public override void OnInvocation(MethodInvocationEventArgs eventArgs)
{
// get the arguments that were passed to the method
object[] args = eventArgs.GetArgumentArray();

// start building a key based on the method name
// because it wouldn't help to return the same value
// every time "lulu" was passed to any method
StringBuilder keyBuilder = new StringBuilder(eventArgs.Delegate.Method.Name);

// append the hashcode of each arg to the key
// this limits us to value types (and strings)
// i need a better way to do this (and preferably
// a faster one)
for (int i = 0; i < args.Length; i++)
keyBuilder.Append(args[i].GetHashCode());

string key = keyBuilder.ToString();

// if the key doesn't exist, invoke the original method
// passing the original arguments and store the result
if (!memos.ContainsKey(key))
memos[key] = eventArgs.Delegate.DynamicInvoke(args);

// return the memo
eventArgs.ReturnValue = memos[key];
}
}
}

That's all there is to it, I modified my factorial method to look like this:
[Memoizer.Memoized]
static int factorial(int n)
{
return n < 2 ? 1 : n * factorial(n - 1);
}

Using this technique, I achieved the results I was looking for. The first time I called factorial(9), it checked the cache, did't find an entry, created one, recursed until it got to factorial(7) where it found a memo, returned it, and stopped the recursion.

This method is pretty expensive and could get pretty memory intensive, but I'm on the lookout for a long process (especially a long recursive process) where I can test this out to see if it produces savings over the long run.