Books I Recommend – Refactoring: Improving the Design of Existing Code by Martin Fowler

June 11th, 2010

0201485672

 

Yet another classic. This book is an extensive compilation of refactorings that range from providing meaningful names for variable to collapsing class hierarchies. Every pattern is introduced in three stages – Motivation, Mechanics, and Example. The Motivation section presents the problem that a refactoring is trying to solve. Then the Mechanics section explains how a refactoring should be conducted. When a refactoring is a combination of other refactorings the author provides references to those refactorings so that you can easily find them in the book. The last part provides a step-by-step example of how a refactoring can be applied to existing code.

The book is neatly organized and can be used a reference book for your everyday programming endeavors.

Copy the code below to your web site.
x 

Books I Recommend – Clean Code by Robert C. Martin

June 10th, 2010

 

Even bad code can function. But if code isn’t clean, it can bring a development organization to its knees.

0132350882

Here is another one of my favorite books. I am not sure if this book needs introduction but if you haven’t heard about it or read it, Clean Code is one of THE books on the art, I would say, of writing code. The book is all about writing clear, readable, and flexible code.

The first part of the book identifies patterns and best practices for writing clean code. Fortunately the book is not simply a compilation of patterns – in the second part of the book Robert C. Martin demonstrates how those patterns fit into real life refactoring scenarios. In the final chapter the author presents a list of code “smells” that can help you identify bad code.

Great book! Enjoy.

Copy the code below to your web site.
x 

Visual Studio Code Snippets for TestClass and TestMethod

March 25th, 2010

Tired of writing [TestMethod] and [TestClass] when creating tests? Well, I got tired and wrote two very simple Visual Studio snippets that can create test classes and test methods.

Just copy the two .snippet files into C:\<Program Files Folder>\Microsoft Visual Studio 9.0\VC#\Snippets\1033\Visual C# , restart Visual Studio and you are good to go.

Enjoy.

Download snippets

Copy the code below to your web site.
x 

Mocking The File System to Improve Testability

December 10th, 2009

Recently I started writing a simple application that would help me organize my music files by automatically renaming them using their tags and moving them to their designated folders.

As expected the program will rely on the file system classes that the .Net Framework provides. Naturally, I wanted to cover the I/O logic with tests so that I am confident that when the software is used it will not do damage to my files and will behave according to my requirements. So I started writing tests…

And here is the catch – in general it is not a good idea to have tests that are performing I/O operations like accessing files and databases. In such situations, but of course not limited to, mock objects are your friend. And before I go into more details about what mocking really is lets find out why mocking I/O is important? Well, for a ton of reasons:

  • Usually faster than performing I/O operations
  • You do not have have to deal with security issues
  • You have more control – easily test intricate scenarios
  • Test setup is far more easier to do 

The first thing that most people think about when asked about mocking is interfaces. And that is no surprise since mocking is built around interfaces. Here is a simplified version of the file system interface that I have created for my application:

public interface IFileSystem
{
    bool FileExists(string path);

    string GetFullPath(string path);

    string GetFileName(string filePath);

    string GetPathRoot(string path);

    string GetDirectoryName(string path);

    string PathCombine(string firstPath, string secondPath);

    void MoveFile(string filePath, string newFilePath);
}

This interface represents all operations that my application will be able to perform on the file system. As we will see, this interface allows me to create a fake implementation of the file system functionality (mock) which will be the cornerstone of all of my I/O tests.

As you have probably guessed I will be using MSTest to drive my tests but you can use a testing framework of your choice. In addition to a testing framework you also need a mocking framework. My favorite one is called Moq – it is very powerful and yet easy to use.

Let’s write some tests…

private Mock<IFileSystem> fileSystemMock;
private IFileSystem fileSystem;

[TestInitialize]
public void Initializer()
{
    this.fileSystemMock = new Mock<IFileSystem>();
    this.fileSystem = this.fileSystemMock.Object;
}

The first thing to do is to create the mock implementation of the interface that we are interested in. This first line of the Initializer  method will create a dummy implementation (mock) of the specified interface (in this case IFileSystem) and you can use the Object property to interact with an instance of the this dummy interface implementation. For convenience we copy the instance reference to “this.fileSystem”.

The mock (“this.fileSystemMock”) allows you to control the behavior of the mocked object and setup assertions which allow you to test the behavior of the mocked object.

The following two tests will assure that the Rename method of the MusicFileConfigurator class behaves according to my specifications. Here is the code that will be tested:

public class MusicFileConfigurator
{
    private IFileSystem fileSystem;

    public MusicFileConfigurator(IFileSystem fileSystem)
    {
        if (fileSystem == null)
            throw new ArgumentNullException("fileSystem");

        this.fileSystem = fileSystem;
    }

    public void Rename(string filePath)
    {
        if(!this.fileSystem.FileExists(filePath))
            throw new FileNotFoundException("File was not found", filePath);

        var newFilePath = this.AdjustNewFilePath(filePath, "renamed.test.file");

        if (this.fileSystem.FileExists(newFilePath))
            throw new IOException("New filename already exists -> " + newFilePath);

        this.fileSystem.MoveFile(filePath, newFilePath);
    }
}

Notice that the constructor accepts a parameter of type IFileSystem. This is very important, as you will see shortly, since it enables us to plug in different interface implementations. This technique is know as Dependency Injection – in this particular case we use the so called Constructor injection. For the sake of simplicity the Rename method will always rename the specified file to “renamed.test.file”.

Back to the tests… First I want to be sure that if a non-existent file is passed as argument the method will throw an exception.

[TestMethod]
[ExpectedException(typeof(FileNotFoundException))]
public void Rename_ThrowsException_WhenTheSpecifiedFileDoesNotExist()
{
    MusicFileConfigurator creator = new MusicFileConfigurator(this.fileSystem);
    this.fileSystemMock.Setup(fs => fs.FileExists(It.Is(s => s == "test.file"))).Returns(false);

    creator.Rename("test.file");
}

The first line, though boring, is crucial for understanding how the test works. Remember that “this.fileSystem” is actually an instance of the mock implementation? Well, now the MusicFileConfigurator is going to use this mock implementation of the IFileSystem.

The second line of the test reveals some of the power of Moq and mocking in general. This line instructs the file system mock to return “false” whenever “test.file” is specified as argument to the FileExists method. By doing that we ensure that the first condition of Rename will not be met and FileNotFoundException will be thrown.

The Setup method is very powerful and allows you to specify how the methods and the properties of your mocked objects behave – what results they returns, whether they throw exceptions and more.

Moving on to a move sophisticated test which asserts that the Rename method can successfully rename the specified file.

[TestMethod]
public void File_IsRenamed_Correctly()
{
    MusicFileConfigurator creator = new MusicFileConfigurator(this.fileSystem);
    this.fileSystemMock.Setup(fs => fs.FileExists(It.Is(s => s == "test.file"))).Returns(true);
    this.fileSystemMock.Setup(fs => fs.FileExists(It.Is(s => s == "renamed.test.file"))).Returns(false);

    creator.Rename("test.file");

    this.fileSystemMock.Verify(fs => fs.MoveFile("test.file", "renamed.test.file"), Times.Exactly(1));
}

Once again we have almost the same setup with just two additional lines. This time we want to test that when the Rename method executes without any errors it will actually rename the specified file. The two Setup statements ensure that the specified file exists and that the new filename does not (which is required by the Rename method).

So far we have just ensured that the Rename method will run without errors. To be sure that it can really rename files we have to make sure that Rename will call MoveFile with the correct arguments. With Moq this is a piece of cake.

Whenever we want to make sure that certain method has been executed or hasn’t been executed we use the Verify method. In this particular setup I want to assert that the Rename method calls the MoveFile method of the file system exactly one time with the expected arguments. If the conditions are not met – for instance the method is called more times – Verify will throw exception and the test will fail. 

I do not know if it is just me but I think that this piece of test code is simply beautiful. In addition to the easily readable fluent interface of Moq you are not dealing with the actual file system which spares you a a great deal of time and resources to setup our tests.

You might be wondering how is the MusicFileConfigurator going to working in a real scenario? Well, I have created a special implementation of the IFileSystem interface which uses the actual file system.

public sealed class DefaultFileSystem : IFileSystem
{
    public string GetFullPath(string path)
    {
        return Path.GetFullPath(path);
    }

    public string PathCombine(string firstPath, string secondPath)
    {
        return Path.Combine(firstPath, secondPath);
    }

    public string GetFileName(string filePath)
    {
        return Path.GetFileName(filePath);
    }

    public void MoveFile(string filePath, string newFilePath)
    {
        File.Move(filePath, newFilePath);
    }

    public bool FileExists(string path)
    {
        return File.Exists(path);
    }

    public string GetDirectoryName(string path)
    {
        return Path.GetDirectoryName(path);
    }

    public string GetPathRoot(string path)
    {
        return Path.GetPathRoot(path);
    }
}

And whenever I initialize the MusicFileConfigurator I do something like that:

class Program
{
    static void Main(string[] args)
    {
        MusicFileConfigurator configurator = new MusicFileConfigurator(new DefaultFileSystem());
    }
}

I have attached the full source code for this article which includes more tests.

Related links:
The Moq Project
Beginning Mocking with Moq

Download File – FileSystemMockingSource

Copy the code below to your web site.
x 

Books I Recommend – I. M. Wright’s Hard Code by Eric Brechner

December 3rd, 2009

I.M. Wright's Hard Code 

I have been yearning to write about this book for a long time since it  had become an all-time favorite. You have got to love this book for its incredible depth, witty jokes, great style, and funky structure. Definitely a must-read for every developer.

Don’t get fooled by the name though – the author covers a lot of ground and the book could be helpful not only to developers but project/product managers, QAs, HR, even top-level management.

Hard Code is a compilation of opinion columns written by the fictitious figure I. M. Wright (got to love the name), or as Eric Brechner calls it “my alter ego”.  In addition to topics like dev schedules, managing risk, agile methodologies, and testing the author covers other more esoteric, yet just as important, ones like people issues and team growth. Moreover the book can be considered as The Hitchhiker’s Guide to Microsoft since it offers quite a few details about the inner-workings of the software giant.

I will leave you with three of my favorite quotes from the book:

“A horse walks into a bar and says: I can code that feature in two days.”

“If you think Agile methods fix all that is wrong with how we build products, you are, in fact, a fool… If you are an anti-Agile curmudgeon who thinks Scrum is an acronym for System of Clueless Reckless Untested Methods, you are as much a fool and just as ignorant”

“If you treat your test team like trash, trash is likely what you’ll ship and trashy is how you’ll feel. If you prefer a smooth release and want to ship a great product, make your test team your ally. … [testers] They cover areas that you can’t or don’t want to do. They keep you on schedule and track. They keep you honest and represent the customer’s perspective.”

Now go read it!

Copy the code below to your web site.
x 

Visual Studio Low Contrast Theme – Zenburn Remixed

September 2nd, 2009

Several months ago I started my hunt for a decent low contrast theme for Visual Studio and I came across a very extensive article on the subject by Scott Hanselman.  I tried several themes but the one that caught my attention was Oren Ellenbogen’s Dark Scheme which is based on the Zenburn theme.

One thing that I do not like about the original themes, being a Silverlight and a WPF developer, is the fact that the XML colors were not configured. In addition to that, the output window uses a horrifying green-colored font that can make your eyes pop. Apart from those two problems I consider the two themes to be the best low contrast themes available.

I have made some adjustments to the original themes and I came up with my version which I use every day. Now the output window uses more subtle font color and the XML markup look a lot better. Here is the Zenburn Remixed:

Zenburn Low Constrast Theme Remixed Code View

Zenburn Low Constrast Theme Remixed XML View

Zenburn Low Constrast Theme Remixed Output Window

I have attached a zip file that contains a Visual Studio 2008 setting file that you can use to apply the Zenburn Remixed theme. To do that just open Visual Studio, go to Tools –> Import and Export settings, and follow the wizard.

Many thanks to the guys that compiled the original themes.

Copy the code below to your web site.
x 

Replacing multiple files with Windows PowerShell

August 23rd, 2009

A couple of days ago I had to overwrite several files with another file and Windows PowerShell came to the rescue. At first it might seem that such task is trivial and it could easily be done in a minute using copy, paste, and Windows Explorer. That might be true if you are dealing with just a few files but if that is not case – if you are dealing with 50+ files which have different names – you should consider another approach.

I have created a simple PowerShell script that will search for specific files in a directory and after that replace those files with a single file, which is specified in the script. Here is the scripts:

$FileName = "C:\new.png"
$TargetDir = "C:\myFolder\"

$FilesToOverride = get-childitem $TargetDir -recurse | where {$_.extension -eq ".png"}

Foreach ($file in $FilesToOverride)
{
    echo ("Replacing " + $file.FullName + " with " + $FileName)
    copy-item $FileName ($file.DirectoryName + "\" + $file.Name)
}

This version of the script will search recursively for all PNG files in myFolder and overwrite every PNG file with new.png. 

The script is very simple but if you are new to PowerShell (like me) you might not be familiar with all of the script’s building blocks. The first one is the “get-childitem” cmdlet. It retrieves items from a specified location, which could be anything – directory, registry, etc. The recurse switch indicates that the scripts will retrieve files not only myFolder but also from all of its subfolders. Get-childitem accepts many parameters which allow you fine tune the search query but that is outside the scope of this post. Here you an find more information about get-childitem.

In its current form get-childitem will return all files in myFolder regardless of their extension. That is where another commandlet comes into play. Where-Object (alias where) cmdlet is used to filter results from other commandlets and I use it in the script to select files with a specific extension (in this case PNG files).

Finally the script goes through the list of all files in FilesToOverride and overwrites each file using the copy-item cmdlet.

Helpful links:

Guide to Windows PowerShell Cmdlets

Piping and the Pipeline in Windows PowerShell

Get-ChildItem Cmdlet

Where-Object Cmdlet

Copy-Item Cmdlet

Download File – Replace Files Script
Copy the code below to your web site.
x 

Resizing Virtual Hard Disk (VHD) Files – The Easy Way

August 2nd, 2009

 

Once in a while you have to change the size of a VHD file and I think I have found the perfect tool for the job. It is called VHD Resizer (previously known as VHD Expander) and it very easy to use. You can grab it from the vmToolKit (http://vmtoolkit.com/) website and expand or shrink the size of any Virtual Hard Disk file with just a few clicks.

Once you start the program you have to select a VHD file to work with and choose how to change the original VHD file.

VHD Resizer Window

You can choose the type of the VHD file (Dynamic or Fixed) and also the new size of the disk in GB or MB units. Click resize and after a couple of minutes, depending on the size of the disk files, you will have the resized file.

Mount the new file onto your Virtual Machine and you are almost ready to go. If you have expanded your VHD file, most probably, the partition that your Virtual Machine uses is not the correct size and the newly added space is reported as unallocated.

Unallocated space

Use your favorite partition management tool, expand the partition, and you are ready to go.

Of course, you could do the geeky thing and use DiskPart utility to change the size of a VHD file. There is lengthy description of this utility called “A Description of the Diskpart Command-Line Utility” that you can find here .

Cheers.

Copy the code below to your web site.
x 

Scheduling multiple builds with a single click (using MSBuild and Team Build 2008)

April 27th, 2009

I have just posted an article about scheduling multiple builds with Team Build and MSBuild at my Telerik blog. Here is an excerpt:

If you are working on a large project it is very probable that the project is composed of several parts/modules which are build separately. What are your options if you want to be able to rebuild the whole thing easily? If you are a Quake tournament winner equipped with Razer Copperhead mouse you could probably schedule 10 builds (in the right order) in a matter of seconds but what about your colleagues that are not so gifted? Well, there is the TfsBuild command line tool but in case you are using the 2008 version and you would like to have the freedom to choose a build agent when scheduling a build you are out of luck. It seems that the only viable option is to write a custom tool that talks directly to Team Build.

You can find the whole blog post here.

Copy the code below to your web site.
x 

Unit Testing Games (Part 1) – Vectors and Transformations

November 25th, 2008

Test driven development and testing in general are mandatory techniques if you are serious about the code that you create. That is especially true in game development where almost every piece of code is very complex. In this first post about testing I will give you a little insight about testing vectors and transformations.

The code that I am going to provide is written for the XNA framework and the Visual Studio testing framework but the concepts that are described in this post can be applied to any game development and testing platforms.

In many cases ensuring that a vector is the one we expect is not as straight forward as writing:

Assert.AreEqual(expectedVector, actualVector).

To illustrate the problem imagine that we have a vector (0, 0, -200), we perform some operations that transform the vector by rotating it around the Y axis by 90 degrees, and we want to assert that the operation is done correctly. You might be baffled to find that after the transformation the vector does not equal exactly (-200, 0, 0), but rather something like (-200, 0, 0.000008742278). This “error” has to do with floating-point numbers and round-off errors. So in order to be able to test our code we have to allow for such imprecision.

The Visual Studio testing framework provides a method that we can use to compare floating-point numbers with a specified tolerance. We just have to build on top of that in order to create a method that we can use for vector comparison. Let’s call the method VectorsAreEqual and inplement it in a class called MathAssert.

public static class MathAssert
{
    private static float precisionDelta = 0.00001f;

    public static void VectorsAreEqual(Vector3 expected, Vector3 actual)
    {
        Assert.AreEqual(expected.X, actual.X, precisionDelta);
        Assert.AreEqual(expected.Y, actual.Y, precisionDelta);
        Assert.AreEqual(expected.Z, actual.Z, precisionDelta);
    }
}

The method is very simple and probably the only question remaining is what a good value for the delta is? The value should be as precise a possible, but at the same time not too precise so it can eliminate the floting-point errors. In my tests I am using a value of 0.00001 which in my opinion is good enough.

Now that we have created our method we can easily compare the vectors (-200, 0, 0.000008742278) and (-200, 0, 0) and assert that they are equal:

Vector3 expectedVector = new Vector3(-200f, 0f, 0f);
Vector3 actualVector = new Vector3(-200f, 0f, 0.000008742278f);

MathAssert.VectorsAreEqual(expectedVector, actualVector);

Transformations are another fundamental part of game programming and being able to test them is crucial. If you are building a scene graph, for example, you probably want to make sure the when a parent node rotates all of its child nodes rotate as well. So we need a way to verify that the resulting transformations are computed as expected. As you might know transformations are composed of linearly independent vectors called basis vectors. A 2D transformation matrix has 2 basis vectors, while a 3D matrix has 3.

2D Transformations

The illustrations above show 3 different two-dimensional transformations and their basis vectors. First (on figure 1) we have identity transformation which does not alter vectors in any way. On the second figure we have a transformation that performs 90 degree rotation of vectors. On figure 3 we have a transformation that performs scaling along the X axis.

As you might know every basis vector corresponds to a single axis of the coordinate space that its transformation describes. In figure 1, for example, the first basis vector corresponds to the X axis and the second vector corresponds to the Y axis. Similarly on figure 2 the first basis vector corresponds to the X axis but the difference there is that the X axis of this transformation points up.
In order to test a transformation for correctness we need to assert that the basis vectors are the ones that we expect.

XNA’s Matrix class can give us a lot of information and we can easily get the basis vectors. The three basis vectors are Matrix.Right, Matrix.Up, and Matrix.Forward. So if we expect to have a transformation that would rotate a vector around the Y axis by 90 degrees we would expect to have (-1, 0, 0) for Forward, (0, 0, -1) for Right, and (0, 0, 1) for Up.

So in order to test a transformation we have to test the 3 basis vectors. For convenience we create a a new method called BasisIsCorrect in our MathAssert class:

public static class MathAssert
{
    private static float precisionDelta = 0.00001f;

    public static void VectorsAreEqual(Vector3 expected, Vector3 actual)
    {
        Assert.AreEqual(expected.X, actual.X, precisionDelta);
        Assert.AreEqual(expected.Y, actual.Y, precisionDelta);
        Assert.AreEqual(expected.Z, actual.Z, precisionDelta);
    } 

    public static void BasisIsCorrect(Matrix basis, Vector3 expectedForward, Vector3 expectedRight, Vector3 expectedUp)
    {
        MathAssert.VectorsAreEqual(expectedForward, basis.Forward);
        MathAssert.VectorsAreEqual(expectedRight, basis.Right);
        MathAssert.VectorsAreEqual(expectedUp, basis.Up);
    }
}

Now all we have to do to test a transformation is to use this method.

Happy testing.

Copy the code below to your web site.
x 

Best books about game development

October 30th, 2008

Since this is my first post I’ve decided to start off with a post that would help anyone that is just starting with game development and is looking for the right books that will get him going.

There are primarily two problems of finding good books about game development. First there are many of them our there. Probably not as many as in some other fields but still you should spend considerable time for research. The second problem is that game development tends to be a very complex and very extensive field and unfortunately not every author can present such complex material in a digestible form.

When I first started with game development I bought about 2 dozen books and as you might expect some of them were great while others proved to be a waste of money. In attempt to save someone some time and money I have listed several books that, in my opinion, are the best.

So here is my list of the best books about game development:

3D Path Primer for Graphics and Game Development

3D Math Primer for Graphics and Game Development

This is one of my favorite books. It is a great source for learning the mathematics behind game development. Important concepts like coordinate spaces, vectors, matrices, quaternions, transformations, etc are clearly explained. The understanding is aided by good illustrations and sample code written in C++. Moreover, the last part of the book introduces many technologies like collision tests, lighting, etc that are used in today’s games and are build upon the concepts introduces in the first part of the book.
Great book.

Introduction to 3D Game Programming with DirectX 9.0c

Introduction to 3D Game Programming with DirectX 9.0c a Shader Approach

Another favorite. Great introduction to the DirectX API. Most importantly the book focuses on the use of shaders and the High-level shading language. The book demonstrates how you can use shaders to create special effects like reflections, shadows, lighting, particle systems, etc.
The latest iteration of this book focuses on DirectX 10. I haven’t been able to check it our so far but I’m sure that it is a must have introduction to DX 10.

Game Conding Complete, Second Edition

Game Coding Complete, Second Edition

One of the best books about computer technologies that I have ever read. Great writing style and most importantly great content. The book explores game development on a higher level by introducing the concept of game engines. If you want to learn about the building blocks of today’s games and how those blocks interact with one another this book is probably the best starting resource available.

Shader X Series

Shader X Series

No doubt one of the best sources for intermediate to advanced knowledge in the field of graphics. Every edition provides a look into cutting-edge computer graphics techniques that take advantage of the latest advancements in computer hardware. Truly a remarkable resource and a must-have.

I have got a couple more good books on my shelves, but I will leave them for another time.
Share your thoughts about my book selection. What are your favorite books?

Copy the code below to your web site.
x