Using CreateSUT() Rather Than TestSetup()

I recently attended a presentation on generics by Jean Paul Boodhoo for the Austin .Net User Group. The presentation was nothing short of amazing for many reasons, but I will save the details of that for another time. For now, I want to focus on a seemingly insignificant practice that I picked up from him there. Within his unit tests, he uses a method called CreateSUT() to instatiate the class under test. (SUT stands for System Under Test.)

[Test]
public void Should_do_something()
{
  VideoGameLibrary library = CreateSUT();
  library.doSomething();
  Assert.IsTrue( library.hasDoneSomething );
}

private VideoGameLibrary CreateSUT()
{
  // Setup dependencies...then instantiate the class to test.
  return new VideoGameLibrary(dependency1, dependency2, etc..);
}

My first reaction to this practice was to think that it was quite useless. I thought to myself “Why not just put it in the TestSetup?” I answered that question on my own today as I began to write some tests for a class that had a lot of constructor-injected dependencies. It took several lines of code to create the dependencies for this class, and then one long line of code to call its constructor and inject those dependencies. The code was ugly, and repeated in every test…can you say code smell? It obviously needed refactoring.

I refactored the tests to remove the duplicated code that created all the dependencies and placed them within the TestSetup(). However, I found my self hesitating to to move the creation of the primary object I was testing. Moving it to the TestSetup() would make the test a bit less clear. I prefer to have as much of a test’s details and dependencies as possible to be declared within the test itself. That way I don’t have to look far to see what I am testing. However, moving this to the TestSetup would result in using class-variables to store the object under test. From the TestMethod’s standpoint, I would just be using a class-variable that had been instantiated somewhere. There would be no apparent details of the creation of the object within the test, so the user would have to look at the TestSetup.

Using CreateSUT() alleviates both the duplicate code and readability issues. You get the best of both worlds. You get to consolidate the setup code into one place, and you get readability by instantiating the system under test right within your test method. This makes it clear which class you are testing, its type, and where to find the code that constructs it.

Because I value clarity so highly, I will definitely be using this pattern in my testing. While on the surface it seems to be next to useless, it does have value.

-=CE=-

Posted in .NET, Test-Driven Development, Testing | Tagged , , | Leave a comment

When To Use a Factory

All too often I see people creating factory or factory methods for objects that could have just as easily been created by their constructor.

The factory pattern is meant to encapsulate the complexity of object creation. If the creation process is not complex, there is little need for a factory.

Here is one example I see quite often:

	class WidgetFactory
	{
		public static Widget Create()
		{
			return new Widget();
		}
	}

In this case, the factory is completely unnecessary. I would venture to say that the following is likewise unnecessary:

	class WidgetFactory
	{
		public static Widget Create(string name, int size, string description)
		{
			Widget widget = new Widget();
			widget.name = name;
			widget.size = size;
			widget.description = description;

			return widget;
		}
	}

In this case, a constructor could have easily taken care of creating this object. So what kind of class needs a factory? The answer is any class that has complex creation. Here is a good example:

	class WidgetFactory
	{
		public static Widget FromString(string widgetExpression)
		{
			WidgetExpressionParser parser = new WidgetExpressionParser();
			WidgetBuilder builder = new WidgetBuilder();
			Widget newWidget = builder.ConstructWidgetFromParsedTree(parser.Parse(widgetExpression));
			return newWidget;
		}
	}

Because constructing this object is pretty complex, it is good to hide the complexity behind a factory. Factories are not bad, but they are often overused. Any time you use a pattern, make sure there is a compelling reason to use it. If you are unsure why you are using a pattern, it is very possible that you are not using it right. Never use a pattern just for the sake of using a pattern.

-=CE=-

Posted in Design, Patterns | Tagged , | Leave a comment

Clarity is the Prime Directive

To write maintainable code, clarity must be our Prime Directive. It is a given that the code must be functional, but it also must be clear. The code must be understood before it to be can be modified. We cannot change code which we do not understand.

Simplicity is the essence of Clarity
Simplicity is something we all strive for as developers. Why? Because if something it simple, it is easy to understand, and thus, easier to change.

Why do we value many smaller objects over fewer large ones? Because the smaller objects are simpler and easier to understand, their purpose is clear.

If you look at many of the practices we do as developers, you will see that they all function to move the code towards a higher degree of clarity. Granted, there are other aspects, but clarity jumps out at me as one of the most important. Maybe its because in my new position I am working with a lot of legacy code that is not clear…it is very difficult to understand.

Clarity should take precedence
When you find yourself having to choose between clarity and other values, lean towards clarity. For instance, if you are following a consistent domain-based naming convention for your objects, but one class seems to be blatantly clearer if its name violated those conventions. Don’t be afraid to violate the conventions for the sake of clarity. After all, conventions often exist to promote clarity. (Generally following the conventions is clearer, but when this is not the case, choose clarity)

If you are using a 3rd party interface that has a confusing name, you can derive a marker interface from it that gives it a clearer name. This derived interface may seem useless since it provides no new functionality, but if makes your code clearer, use it. Choose clarity over the desire to remove what you feel is useless code.

public interface IVideoCollection : IPoorlyNamedInterface<Video> {}

Naming is important
Given that clarity is so important to coding. It places much more emphasis on smaller, seemingly less-important practices such as using well-chosen names. Naming is one of the most important factors in keeping your code clear and easy to understand.

A name for a method should sufficiently explain what that method does such that the reader does not have to look at the implementation of that method to determine what it does.

There are times where I have debated a name for a single class for over an hour. But the result was worth it. Many times a name I have chosen may seem good for an object, but after a bit of discussion with others, another name emerges that is much better and leads to further insight of the object model. Using an online thesaurus is a good way to get great ideas for names that you may not have otherwise thought of. The right name will result in clarity.

Summary
Clear code is code you don’t have to look at for long to know what it does. It is clear in and of itself. When choosing a solution for a design problem, or choosing a variable or class name, lean towards clarity over other values.

Posted in Design, Principles | Tagged , | 1 Response

Why Static Methods Are Bad

Disclaimer: I am a firm believer that you should never say never…whoops, just contradicted myself. Well, you know what I mean: Most principles in development are not hard and fast. There are always cases for going against the grain. Every valid principle has an equally valid exception case where disregarding the principle can be advantageous. While I feel there are valid uses for static methods, for the most part I believe they are destructive to a codebase.

Static methods spread dependencies throughout your code making it difficult to test and maintain. I don’t remember who said it, but someone referred to the use of static methods as the “Dependency Broadcaster” pattern. Its very true. Once a method depends upon a class’s static method, it depends upon that class explicitly. You cannot mock the dependency, you cannot inject it…it is hardcoded. This is not good!

Haven’t you heard the statement “Don’t use global variables?” There is a reason not to use global variables or global functions: you can’t immediately see where they are used. Moreover, if you are trying to test something, you can’t replace that global variable without affecting every part of the system that uses it. Dependecies on global variables are hidden. You don’t know what you are affecting when you change them.

Static methods are the “global variables” of the Object-Oriented age. That’s what static means…unchanging…always the same, everywhere…global. Stay away from these when you can. While there are valid uses for static methods, most of the time you can do without them. Use Dependency Injection or some other technique to avoid their use when possible. You will thank yourself later.

Posted in .NET, C#, Design | Tagged , , | Leave a comment

Smaller User Stories = More Accurate Estimates

The larger your user stories are, the less accurately you are able to estimate them
The smaller your user stories are, the more accurately you are able to estimate them

At the new company I work at, one of the biggest problems they have had in the last few sprints is a lack of accuracy in story estimates. They did not complete all the work in the last sprint because they under-estimated the time it would take to do so. While there are many factors that contribute to the accuracy of estimates, I would like to focus on one: User Story size.

I propose that smaller stories are easier to estimate accurately, whereas large stories are not.

A small story has a shorter duration, less functionality and fewer unknowns and thus, less room for error. However, a large story contains a lot of functionality, and a longer duration, and therefore much greater room for error.

A large user story has much more room for unknowns, and the fact that it is large, and not broken down to a more granular level may indicate that the details have not yet been fully thought through. The estimates are less likely to be accurate because there is a lack of understanding of the functionality to be implemented. However, using smaller user stories forces the developer to break down large stories into smaller ones, and in the process, think through the stories in a higher level of detail. In doing so, the developer gains more understanding of the functionality and exposes more of the unknowns. Thus, the estimates will be more accurate.

In projects I have worked on in the past, our estimates have been surprisingly accurate. In those projects, estimating fine-grained stories was the key to that accuracy. If you feel your accuracy is suffering, try to start using smaller stories. I have found that stories that are less than 2 days or so are ideal. I would break them down into tasks with a duration of no more than 8-10 hours (most of our tasks were estimated at 2-6 hours of uninterrupted programming time). These figures are not cast in stone…they worked well for the project I was on, but every project is different. Find what works for you and stick with it.

-=CE=-

Posted in Agile | Tagged | Leave a comment