Monday, 22 June 2009

PartCover - an alternative to NCover?

I've been looking for a cheap or free tool for measuring NUnit test coverage and just stumbled upon PartCover. I've installed it and fiddled with it and it seems to be an OK tool. It's Open Source, too - which I think is great.

I have to say, though, that the documentation is poor and the application itself is buggy (I experienced a critical exception when trying to save a coverage report to file). Despite this, I'll take a buggy PartCover over NCover which would set me back $650 for a license!

Might write more about this later. Check it out!

Friday, 13 March 2009

Names and the Importance of Semantics

I've taken the below 'post' from some documentation I've recently written for the developers where I'm currently working. It appears to me that, in general, developers (and, indeed, architects) spend far too little time thinking about names and naming conventions. Personally I spend hours thinking about names. Good names are an incredibly important aspect of good software design. Anyway - if you care to read on, this is what I've said on the subject so far:

Aside from writing code that is correct, efficient, and actually works, the most important aspect of software development is, arguably, naming. Choosing good names for namespaces, classes, methods, and properties (even member variables, local variables and parameters) is incrediby important (and therefore also difficult) because the semantics they convey. A name must be unambiguous and clearly convey the purpose and function of the named component when viewed in isolation, as well as when it is viewed in the context of its root namespace, immediate namespace, class, and so on.

Good type and namespace names leave little room for misunderstandings and mistakes because of ambiguity. Namespaces and types defined in the .NET Framework are very clearly named throughout and the semantics of each name are typically very clear. A good example of this is the System.IO namespace.

The System.IO namespace name is unambiguous because it is short, because the relationship between the components of the namespace ("System" and "IO") is clear, and because each component of the namespace is named well semantically:

"System" implies a logical grouping of functionality that is 'close to the machine' or 'close to the framework'. The "System" namespace, by virtue of its name, is very clearly not a task or application specific namespace.

While it may be argued that the word "System" is ambigous because it can encapsulate so much functionality (and varied functionality at that), when seen in its context (it is the main root namespace of the entire framework) the name is still very clear.


"IO" is a very old and commonly used abbreviation ("InputOutput") in computer science and is always associated with data transfer between devices (both internal and peripheral). The immediate association of "IO" is that of file read/write operations, and this is exactly the kind of functionality that the classes in this namespace provides.

System.IO is therefore a really good namespace because the semantics of the first component's name lends meaning to the other. "System" tells the developer that we're dealing with general, non application-specific functionality, and "IO" implies that the functionality is file-operation specific.

The File class within the System.IO namespace is another good example of good naming. Its fully qualified name, System.IO.File, makes it absolutely clear what the class is and what it does - it's very clearly a representation of a file on a file system and provides file operations to the caller.

The methods on the File class are also very well named. A couple of examples illustrate how clear, short names can convey a lot of information when viewed in their proper context:

public static System.IO.FileStream Open(string path, System.IO.FileMode mode)

The method name File.Open is in itself very clear; it is obvious that the Open() method will open a file on a disk. There is sometimes a tendency to be too specific when naming methods - the above method might for example be called OpenFile(). Viewed entirely in isolation, the second method name, OpenFile(), is clearer than Open() - but when viewed in the context of its class, OpenFile() is obviously a poorer name than Open() because the context (the File class) already makes it obvious that we are in fact dealing with files!


public static bool Exists(string path)

This method name is clear because it can be phrased as a question with a simple yes/no (or true/false) answer: "Does this file exist?"

public static void Move(string sourceFileName, string destFileName)

This method name is unambiguous (clearly File.Move() is a method that moves a file on a file system), but pay particular attention to the parameter names; sourceFileName and destFileName leave no doubt about what you are dealing with. If this method's signature is paraphrased into a sentence it would read something like "move this source file to this destination."

The above examples above illustrate the importance of context when constructing names in software. A named element must make sense in isolation, but it is also very important that it makes sense contextually. Methods must be named so that the name itself carries the correct semantics, but the method's parameters (and return type) should be named in a manner so as to add further semantic value to the method's signature.

Tuesday, 10 March 2009

Orange Mocha Frappucino

This is just a quick note to those of you that I know read this blog - because I know you know Steve. He's started blogging over on Orange Mocha Frappucino. First post is about handling web.config in unit tests. Good one, Steve!

Tuesday, 24 February 2009

James Joyce .NET

Last week, after doing a code review, I coined the term "James Joyce .NET". Though the James Joyce factor isn't particularly .NET specific (I'm sure there are Ruby, C++, Java, and most certainly C developers out there who do things in similarly cryptic manners), I think the term has a nice ring to it. And in fairness to Joyce, I think the code I reviewed was far less readable than Ulysses.

Aside from software that works and "does its thing" in a reliable manner, clients care a lot about code that's maintainable. The client may not know that they care about this, at least not at first - but once you tell them that a change is going to take three weeks to complete "because of this, that, and the other" (because the code you've written isn't maintainable) you bet your sweet ass they start caring. They care not because of the state of your code; they care because of the cost. And rightly so.

There are many key things to consider when writing maintainable code but the subject of my current rant will be readability. Does your code read like a book? Probably not (hey, it's not fiction) - and that's OK. But do your method names and signatures read like sentences? Could you translate the body of your methods into short little textual paragraphs that clearly illustrate what they do? If you answered "no" to both of these questions it's probably time to stop and think a little.

Disclaimer: I'm renowned for harping on about ideals and I've been caught out many a time falling short of my own mark. That said, I stick to my ideals because without them we've got nowhere to go.

To start with, code must be legible. That means you have to choose names (for your classes, methods, parameters, variables) that clearly indicate purpose. Favour readability over brevity when creating names. Second, your names must make semantic sense. A class-method name combination should be completely unambiguous, easy to read, and clearly convey "what you get". Classes and methods should do what it says on the tin. Don't be obscure, don't be ambiguous.

Third: Use the appropriate constructs for the job. Don't embed an algorithm in a property. Don't use private properties. Properties are there to expose aspects of a class, so if you're not going to expose it, use a private member variable instead. Don't use indexers for anything but accessing collection data. Don't use generics unless you need generic code, and then only if generics give you something that a typed parameter list doesn't (using interface/abstract classes instead of concrete types).

Seriously, think long and hard about any code you write. Just because something works doesn't make it good. And give some thought to those people that come after you. Will they be able to understand what you've done? You might very well be a genius and the best thing since sliced bread but really, what good is that if nobody understands what you've done? Don't obfuscate your code by being lazy, too clever, or by using constructs in a way that they were not intended.

</ rant>

Wednesday, 18 February 2009

What not to do 5 minutes before a meeting...

I typically don't read the Metro magazine on my way to work, but today I did. And there was a little snippet in there about a YouTube video that was supposed to be very funny. This tickled my curiousity, so when I found myself with a couple of minutes to spare before a meeting this morning, I went to YouTube to watch the clip about David After Dentist.

Bad decision. It took me a good 10 minutes to stop grinning and get my sudden bursts of laughter under control. Not good when someone's called a meeting with you to give you an update on serious matters.

Funny as hell though :-)

Thursday, 13 November 2008

Brittleware

This is really just an observation, and a highly subjective one at that. To any die-hard ASP.NET traditionalist out there: This isn't meant as an attack, so don't take it as one.

I've been working on the ASP.NET MVC framework together with my buddy Steve for a while now and we've been trying out a lot of different things while getting to grips with this new (and much better) way of doing things. We've been trying to establish our own patterns for developing MVC applications, and while doing so we have experimented and written a lot of code, and very few tests.

During this phase of experimentation I truly came to love the MVC framework for its flexibility and elegance, but for some reason I had this nagging feeling that all was not well. It was a familiar feeling, too, and one that I associate specifically with web development. But I couldn't put my finger on it.

Then just a couple of days ago I realised what it was. We'd decided to start building in earnest, and using the MVC framework in anger. Nothing would be written unless it was tested. And after a couple of hours of intense controller-testing I suddenly realised that the uneasy feeling was gone, and in its place was a feeling of security and contentment.

What I'd felt before was the same feeling I always had when writing ASP.NET applications. Things just felt brittle and ready to break. I could go to any length in order to ensure that the application did what it should, worked like intended, and would fail gracefully - but somehow that feeling of brittleness never went away completely. I didn't have any tests, no way of verifying that I was still on the right path, the straight and narrow. And writing MVC applications without tests gave me that same feeling because really, I was no better off.

With the introduction of tests that feeling of brittleness disappeared and instead the application felt robust. Solid. Stable. Reliable. Add any number of synonyms. If you believe in TDD you know what I'm talking about.

I don't know if there's a moral to this story, but the realisation I had has confirmed to me yet again how correct it is to develop everything with tests first. There simply isn't another way.

Wednesday, 29 October 2008

Ninject providers and Moq mock injection.

A few months back I stumbled upon Ninject while reading a post on Jonas Follesø's blog. Since then I've been busy architecting a very modular e-commerce solution for a client, and just recently have I started "tying the application together" using Ninject. Ninject makes for very simple dependency injection, indeed. The Ninject approach is so straight forward, in fact, that Ninject isn't just a good framework for Inversion of Control (IoC) - it's an excellent tool for teaching the principles of IoC as well.

I'm not going to go into any detail on how to use Ninject here, though - there are lots of guides and tutorials in the Dojo.

What I will talk about here, however, is a nice little solution for injecting mocked objects using a Ninject binding provider. My solution uses a Service Locator similar to the one Jonas sets out in his article on Silverlight and Ninject, but the focus here is on the binding providers and how to use them in a unit testing scenario. Nonetheless, a quick look at how the Service Locator is used will not go astray.


public class ServiceLocator
{
public IKernel Kernel { get; private set; }

public static ServiceLocator Instance { get; private set; }

public T Get<T>() { return Instance.Kernel.Get<T>(); }

public ServiceLocator(params IModule[] modules)
{
Kernel = new StandardKernel(modules);
Instance = this;
}
}


As you can see, the ServiceLocator class is a singleton. You load it up once for your application, and classes can happily use it to get access to instances of types defined by an interface, such as


ICategoryService svc = ServiceLocator.Instance.Get<ICategoryService>();


I'm building MVC web applications where the controller classes resolve their dependencies in this way, and in order to test these controllers I have to provide the ServiceLocator with bindings to mocks. But I'm probably getting ahead of myself just a little.

Right... I realise I actually have to provide at least a little information on how Ninject works so that you, dear reader, have at least some context. In order to facilitate dependency injection via Ninject, you create a kernel and load this with one or more instances of IModule which contain your bindings. Creation of the kernel might look something like


StandardKernel kernel = new StandardKernel(new MyBindingModule());


where MyBindingModule is a class that contains the bindings I require. Once again, for the sake of brevity I will not explain the intricate detail of how all this works, but for the sake of continuity this is how MyBindingModule might look


public class MyBindingModule : StandardModule
{
public override void Load()
{
Bind<ICategoryService>().To<CategoryService>();
}
}


By creating a kernel and passing in MyBindingModule to it, the kernel will know that whenever you request an instance of ICategoryService it should create a new instance of the concrete class CategoryService and return that back to you.

Now, that's really great and really powerful stuff. You can set up loads of different bindings, even conditional bindings, and the kernel will happily resolve these for you and return you the right instance type whenever you need it. The only issue with this setup is that when it comes to unit testing, where you need to replace some of your standard bindings with mocks, this approach doesn't work.

Why not? Because the kernel, by default, will resolve a binding and return a new instance of the resolved type. If you're going to use mocks, this is no good because you need to have a handle on the actual mock instance so that you can set expectations and verify behaviours etc etc.

Thankfully Ninject's got a nice little feature which allows you to bind a type to a provider. The provider is a class (which you create) that's responsible for creating the object the kernel should return. Typically you'd use a provider when creation of an object is a complex task (e.g. it involves reading configuration files etc). We're not going to create a very complicated object, but we'll use a provider class so that we can ensure that the Ninject kernel resolves its bindings to specific mock instances that we've already created - rather than creating new instances that we have no access to.

Before we go any further, let's just have a look at a simple test that injects a mock into another class. In this test we're going to create a mock for ICategoryService, set an expectation on that mock, then inject the mock into a CategoryController class (by means of its constructor), ask CategoryController to do something for us, and lastly verify that the CategoryController used the mock in the way we expected. Moq's my mocking framework of choice, but you could use any other framework if you like (Rhino Mocks, NMock, EasyMock, TypeMock etc).


[Test]
public void TestAddingCategoryReturnsTrueFromService()
{
Category category = new Category(){ Id = 100};

Mock<ICategoryService> serviceMock = new Mock<ICategoryService>();
serviceMock.Expect(x => x.Add(category)).Returns(true);

CategoryController controller = new CategoryController(serviceMock.Object);
controller.AddNewCategory(category);

serviceMock.VerifyAll();
}


If you are at all familiar with mocking you'll the above test (created with NUnit) should present no mystery (other than it's a bit pointless, perhaps).

We're going to change the scenario a bit, because we've no control over the creation of CategoryController instances, so we can't inject dependencies via the constructor. Instead we'll let the CategoryController's default constructor make use of the ServiceLocator to resolve its dependencies:


public class CategoryController
{
private ICategoryService CategorySvc { get; set; }

public CategoryController()
{
CategorySvc = ServiceLocator.Instance.Get<ICategoryService>();
}
}


Now we can no longer inject the mock directly into our the CategoryController. Instead we have to rely on Ninject to resolve the dependency for us. So now we'll load up the ServiceLocator with an IModule that has a binding to a provider that we can prime with our mock. Hang on tight while we we have a look at our provider:


public class NInjectMockProvider<T> : SimpleProvider<T> where T : class
{
public static Mock<T> Mock { get; set; }

protected override T CreateInstance(IContext context)
{
if (Mock == null){ Mock = new Mock<T>(); }
return Mock.Object;
}
}


It's straight forward, really. Our NInjectMockProvider<T> extends SimpleProvider<T>. The CreateInstance(IContext context) method creates an instance of Mock<T> and assigns this to the static property Mock, unless this is not null, and then returns the mocked object. Armed with this very simple provider and a new binding our test takes on a new shape alltogether. I've included the new test and binding below.


[Test]
public void TestAddingCategoryReturnsTrueFromService()
{
//set up the ServiceLocator
ServiceLocator locator = new ServiceLocator(new MyBindingModule());

Category category = new Category() { Id = 100 };
Mock<ICategoryService> serviceMock = new Mock<ICategoryService>();
serviceMock.Expect(x => x.Add(category)).Returns(true);

NInjectMockProvider<ICategoryService>.Mock = serviceMock;

//this is where the magic happens. The mock's been assigned to the provider, so
//the controller will be automagically injected with the mock instance we
//created above.
CategoryController controller = new CategoryController();

controller.AddNewCategory(category);

serviceMock.VerifyAll();
}

public class MyBindingModule : StandardModule
{
public override void Load()
{
Bind<ICategoryService>().ToProvider(new NInjectMockProvider<ICategoryService>());
}
}


This example is specific to a scenario where we use the Service Locator pattern, but you can use the same approach and the same mock provider class in other situations as well where you'd like Ninject to resolve bindings to existing mock instances.

I've found that the use of NinjectMockProvider<T> makes it easy to inject mocks and easy to read and understand the tests as well. Hopefully this can be of use to some of you out there.