Wednesday, May 7, 2014

Test Drive that Fizz Buzz

Fizz Buzz is a game where you count upwards saying the numbers aloud with a slight twist to try and trip you up. When a number is divisible by 3 you say "Fizz", when a number is divisible by 5 you say "Buzz" and if the number is divisible by both 3 and 5 you say "FizzBuzz". The straight forward rules of Fizz Buzz makes it an ideal problem to solve as a TDD kata as it allows you to focus on TDD practices as opposed to the implementation details.

The goal of a TDD kata is to allow you to follow the red, green, refactor pattern over and over. The idea is to first write a failing test (red), write the minimum implementation to make that test pass (green) and then refactor your code as necessary to make it more maintainable / readable.

On with the kata...

Test 1 - Instantiating FizzBuzzer does not throw an exception
Write the failing test:

1
2
3
4
5
[Test]
public void FizzBuzzer_Instantiating_ShouldNotThrowAnException()
{
  Assert.DoesNotThrow(() => new FizzBuzzer());
}
Red - This test will not compile as the FizzBuzzer class does not exist yet.

Write the minimum so the test will pass:

1
2
3
public class FizzBuzzer
{
}
Green - The test now passes.

Refactor - Nothing to refactor.

Test 2 - Value not divisible by three or five returns value
Write the failing test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
[Test]
public void Convert_ValueNotDivisibleByThreeOrFive_ShouldReturnValue()
{
  //Arrange
  int valueToConvert = 1;
  string expectedValue = "1";
  FizzBuzzer fb = new FizzBuzzer();

  //Act
  string result = fb.Convert(valueToConvert);

  //Assert
  Assert.That(result, Is.EqualTo(expectedValue));
}
Red - This test will not compile as the FizzBuzzer class currently does not have a Convert method. The test follows the "Triple A" unit test structure. This is generally considered a best practice when writing unit tests to provide them with a consistent structure. The test also utilizes NUnit's Assert-That-Is syntax for its assertions which makes the assertions themselves more human readable - For example the above assertion reads like "Assert that result is equal to expectedValue".

Write the minimum so the test will pass:

1
2
3
4
public string Convert(int valueToConvert)
{
  return valueToConvert.ToString();
}
Green - The test now passes and the minimum functionality has been written. It is tempting to write more than is actually required but resist this otherwise you will find yourself writing additional unit tests after implementing the functionality or gold plating your code with functionality you necessarily do not actually need.

Refactor - Nothing to refactor.

Test 3 - Value divisible by three returns "Fizz"
Write the failing test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
[Test]
public void Convert_ValueDivisibleByThree_ShouldReturnFizz()
{
  //Arrange
  int valueToConvert = 3;
  string expectedValue = "Fizz";

  FizzBuzzer fb = new FizzBuzzer();

  //Act
  string result = fb.Convert(valueToConvert);

  //Assert
  Assert.That(result, Is.EqualTo(expectedValue));
}
Red - The test fails as it will return "3".

Write the minimum so the test will pass:

1
2
3
4
5
6
7
public string Convert(int valueToConvert)
{
  if (valueToConvert % 3 == 0)
    return "Fizz";

  return valueToConvert.ToString();
}
Green - The test passes as "Fizz" is returned when valueToConvert is divisible by three - The modulus arithmetic operator is used to check for this.

Refactor - There is some refactoring to be done here. There is some duplication now within the previous two tests: FizzBuzzer fb = new FizzBuzzer(); This can be extracted to a test setup method that is run before each test is executed.

Refactored test code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
private FizzBuzzer _fb;

[SetUp]
public void Setup()
{
  _fb = new FizzBuzzer();
}

[Test]
public void Convert_ValueNotDivisibleByThreeOrFive_ShouldReturnValue()
{
  //Arrange
  int valueToConvert = 1;
  string expectedValue = "1";   

  //Act
  string result = _fb.Convert(valueToConvert);

  //Assert
  Assert.That(result, Is.EqualTo(expectedValue));
}
A private FizzBuzzer (_fb) variable has been declared with class scope. This is instantiated within the Setup method which is called before each test is executed because of it's [Setup] attribute. After refactoring your code, always re-run your unit tests. This practice will help ensure your refactoring has not broken anything.

The //Act and //Assert steps within each test are also duplicated and could be extracted out into a separate method. However, to help practice the "Triple A" pattern I have chosen to leave them in each of the unit tests.

Test 4 - When value is divisible by five return "Buzz"
Write the failing test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
[Test]
public void Convert_ValueDivisibleByFive_ShouldReturnBuzz()
{
  //Arrange
  int valueToConvert = 5;
  string expectedValue = "Buzz";

  //Act
  string result = _fb.Convert(valueToConvert);

  //Assert
  Assert.That(result, Is.EqualTo(expectedValue));
}
Red - The test fails as it returns "5".

Write the minimum so the test will pass:

1
2
3
4
5
6
7
8
9
public string Convert(int valueToConvert)
{
  if (valueToConvert % 3 == 0)
    return "Fizz";
  if (valueToConvert % 5 == 0)
    return "Buzz";

  return valueToConvert.ToString();
}
Green - The test passes

Refactor - Nothing to refactor

Test 5 - When a value is divisible by three and fizz return "FizzBuzz"
Write the failing test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
[Test]
public void Convert_ValueDivisibleByThreeAndFive_ShouldReturnFizzBuzz()
{
  //Arrange
  int valueToConvert = 15;
  string expectedValue = "FizzBuzz";

  //Act
  string result = _fb.Convert(valueToConvert);

  //Assert
  Assert.That(result, Is.EqualTo(expectedValue));
}
Red - The test fails as it returns "Fizz".

Write the minimum so the test will pass:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public string Convert(int valueToConvert)
{
  if (valueToConvert % 3 == 0 && valueToConvert % 5 == 0)
    return "FizzBuzz";
  if (valueToConvert % 3 == 0)
    return "Fizz";
  if (valueToConvert % 5 == 0)
    return "Buzz";

  return valueToConvert.ToString();
}
Green - The test passes.

Refactor - The Convert method has some duplicate modulus calculations which can be refactored and some improvements can be made to make the method more readable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public string Convert(int valueToConvert)
{
  bool isFizz = valueToConvert % 3 == 0;
  bool isBuzz = valueToConvert % 5 == 0;

  if (isFizz && isBuzz)
    return "FizzBuzz";
  if (isFizz)
    return "Fizz";
  if (isBuzz)
    return "Buzz";

  return valueToConvert.ToString();
}
This refactoring extracts the fizz and buzz modulus calculations into their own boolean variables to represent if valueToConvert is divisible by three or five. These boolean variables are used to return the correct conversion. This refactoring has rippled throughout the whole of the convert method - Running the previously written unit tests will prove that no functionality has been broken.

That completes the Fizz Buzz TDD kata.

Continuing further, you could re-factor the FizzBuzzer implementation to only use a single return statement and use the existing unit tests to confirm you have not broken any functionality. This is an important factor to remember when writing a unit test: The test should not know about any of the implementation details of what it is testing. See my blog post about a ##DDD North## session I attended to read more about this.

The projects full source code can be found here.

Fizz Buzz is an excellent problem to help you get into the TDD mindset. It allows you to focus on the red, green, refactor pattern without becoming too bogged down with implementation details. To help keep things interesting, you can also attempt many different implementations of the FizzBuzzer class when you attempt the kata.

Sunday, March 16, 2014

SSRS - Tip: Passing multiple values in a single parameter within a stored procedure

When modifying a drop down selector in a SSRS report to allow a user to select multiple values I noticed all other reports which provided this functionality had the accompanying SQL query embedded within the report. I thought this was strange as the majority of the other SSRS reports I had looked at used stored procedures.

After a little bit of research I found the following:
"The data source cannot be a stored procedure. Reporting Services does not support passing a multi-value parameter array to a stored procedure." Essentially, SSRS passes the multi-value parameter as a comma separated string to a stored procedure. 
Note: If the SQL query is embedded within the report, this format works perfectly fine: "IN ('Item 1', 'Item 2', 'Item 3')"

All is not lost if you do not want to embed your SQL within the SSRS report. If you read this excellent article written by David Leibowitz Puzzling Situations: Using MultiValue Parameters with Stored Procedures in SSRS, it is possible (and quite straight-forward) to write an SQL function that will convert the comma separated string into a table. The table can then be enumerated using the IN keyword within your stored procedure.

Happy days!

Wednesday, March 12, 2014

Creating local domain with IIS

Recently, I gave a presentation that required webpages to be loaded from multiple domains:



Instead of registering multiple domains and publishing a couple of websites, I was able to achieve this locally through these simple three steps.

1) Add a new Web Site

Open Information Internet Services Manager (the easiest way to do this is to search for "IIS" from the Start menu) and expand your localhost entry in the tree on the left hand side exposing the "Sites" node. Right click on this and select "Add Web Site...".


2) Configuring the new Web Site


The most important thing to notice here is that the "Host name" must match the domain that you want to create locally. With the above configuration, I would expect to access this site by navigating to "www.mygoogle.com" in a browser.

3) Configure the HOSTS file

The last step is to force your computer to resolve requests to your domain to your local IIS instance and not resolve them through a DNS. This is achieved by adding a entry to the HOSTS file that points to your local machine. In Windows XP, Windows Vista, Windows 7 and Windows 8, the hosts file can be found here: c:\windows\system32\drivers\etc\HOSTS.


Any requests for "www.mygoogle.com" will now be resolved to the IP address of 127.0.0.1, which is the loopback address for you machine resulting in your local IIS serving the page:


Sunday, March 2, 2014

MSSQL Maintenance Plans - Tip: Have the task name displayed in your logs

When viewing the history of a Maintenance Plan job, the name of each task can be blank making it tricky to know which row relates to which task.


When creating the Maintenance Plan task, unless a "Task Name" is specified (Properties on the specific task), no name will be displayed within the plans history. 


By adding a "Task Name", your plan history will display the task name at the row level. This helps make the plans history more readable at a glance.




Saturday, February 15, 2014

Roman Numeral Converter and the Strategy Pattern

The Roman numeral converter is a converter that will converter a decimal value (Eg. 4) to its Roman numeral equivalent value (Eg. IV).

This implementation of the converter (of which there are many other alternative implementations) uses a divide and conquer approach. The conversion is broken down into smaller "bite size" parts (ones, tens, hundreds, thousands) which lends itself nicely to using the strategy pattern.

What is the Strategy pattern?
The strategy pattern is a way to encapsulate a family of similar algorithms. Each algorithm is a strategy and the pattern allows one or many strategies to be selected at run-time.

The strategy interface
Each strategy is required to implement an interface so it can be consumed by the client consistently. The IConverter interface is used to achieve this and specifies a single method called Convert.

1
2
3
4
public interface IConverter
{
  string Convert(int number);
}

A strategy implementation
The OnesConverter implements the IConverter interface to convert the ones (1 - 9) to their Roman numeral equivalents. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class OnesConverterStrategy : IConverter
{
  public string Convert(int number)
  {
    int onesToConvert = CalculateNumberOfOnesToConvert(number);

    string conversion = string.Empty;

    int i = 1;

    while (i <= onesToConvert)
    {
      if (i == 4)
        conversion = "IV";
      else if (i == 5)
        conversion = "V";
      else if (i == 9)
        conversion = "IX";
      else
        conversion += "I";
      i++;
    }

    return conversion;
  }

  private int CalculateNumberOfOnesToConvert(int number)
  {
    int numberOfOnes = number % 10;

    return numberOfOnes;
  }
}

Each converter follows a similar pattern where the CalculateNumberOfXXXXToConvert method uses a modulus calculation to determine the number of units (number of tens or number of hundreds etc.) to convert to Roman numerals. This is used within a while loop to generate the conversion.

Roman numeral converter
The RomanNumeralConverter class instantiates a List<IConverter> in the order in which they will be called (thousands > ones). It then enumerates through this list building up the Roman numeral conversion as it progresses and returns the completed conversion to the caller.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class RomanNumeralConverter
{
  private List<IConverter> _converters;

  public RomanNumeralConverter()
  {
    _converters = new List<IConverter>
    {
      new ThousandsConverter(),
      new HundredsConverter(),
      new TensConverter(),
      new OnesConverter()
    };
  }

  public string ConvertToRomanNumerals(int number)
  {
    if (number <= 0 || number > 3000)
    return "Invalid value";

    string result = string.Empty;

    _converters.ForEach(x => result += x.Convert(number));

    return result;
  }
}

The benefits of this approach is that each of the strategy implementation can be tested in isolation and allows the RomanNumeralConverter to be extended by introducing additional converters without effecting the existing converters (as long as the converter initialization order is preserved).

The downside to this implementation is that there is a bit of duplication in each of the converters as essentially the algorithm is the same but only the Roman numerals change. A single converter could be potentially used here which could use a multi-dimensional array to switch which Roman numerals to use based on the place value (ones, tens etc.) of the decimal number currently being converted.

The complete project can be found here with accompanying unit tests.

In a subsequent post, I will extend the RomanNumeralConverter to use a factory to generate an enumerable of IConverter strategies based on the decimal value required to be converted. This will allow us to further utilize the strategy patterns ability to load specific strategies at run-time and introduce the factory pattern.

Saturday, December 28, 2013

Creating an IoC Container - Method Chaining Syntax

This is the forth part of a series on creating an IoC container. In the third part, the container assumed responsibility for an objects lifetime by managing creating it as a singleton or not. In this part, I will delve into making the registration process more readable through the use of method chaining. This is the approach that is currently being used by the open source IoC container called StructureMap.

Method Chaining

Method chaining allows a series of methods to be called one after another. The first method call will return an object that contains the next method to be called and so on. This allows a series of actions to be carried out and for the code to be represented in a very readable manner.

Making it More Readable

This is the container's current registration syntax:

container.register<IAbstractType, ContreteType>(isSingleton: true);

From that single line of code, it is not clear that the first generic argument is the requested type and that the second is the return type. If you had never used the container before, you could very easily get them mixed up. Through using method chaining, a more readable registration syntax can be created that will look like this:

container.For<IAbstractType>().Use<ConcreteType>().AsSingleton();

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public RegistrationExpression For<T>()
{
  var abstractType = typeof(T);

  var registration = new Registration()
  {
    AbstractType = abstractType
  };

  _registrations.Add(registration);

  var registrationExpression = new RegistrationExpression(registration);

  return registrationExpression;
}

The For method is where the requested type is specified. The first half of the implementation is the same as the Register method, however, the Registration object is only being populated with the AbstractType before it's added to the internal collection of registrations. The final act is to create a RegistrationExpression object with a reference to the Registration.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class RegistrationExpression
{
  private readonly Registration _registration;

  public RegistrationExpression(Registration registration)
  {
    _registration = registration;
  }

  public RegistrationExpression Use<T>()
    where T : class
  {
    _registration.ConcreteType = typeof(T);

    return this;
  }

  public RegistrationExpression AsSingleton()
  {
    _registration.IsSingleton = true;

    return this;
  }
}

The RegistrationExpression object is what enables the method chaining as it contains the other behaviors relevant to completing a registration. All the methods return this (in this case, the RegistrationExpression) and it is this that allows subsequent methods to be called in a chain. These methods update the Registration through the reference stored in the private _registration variable that was supplied when the object was created.

A complete project containing all the source code for the container and a set of unit tests can be found here.

Saturday, December 7, 2013

Creating an IoC Container - Singleton

This is the third part of a series on creating an IoC container. In the second part, I extended the container to handle instantiating types that received dependencies via their constructor. In this part, I will focus on how to mark a type as a singleton and how to resolve it as such.

What is a Singleton?

A singleton can be thought of as where there is only one instance of a class in existence. Every time an object is instantiated using the new keyword, it is a completely new object that is created. This means that if the same type was "newed-up" three times, there would be three separate objects living on the heap. The behavior of a singleton is the opposite to this where only one instance should ever be in existance. As an IoC container is responsible for instantiating and serving objects, it is the perfect place to manage their lifetime too.

Registration

1
2
3
4
5
6
7
public class Registration
{
  public Type AbstractType { get; set; }
  public Type ConcreteType { get; set; }
  public bool IsSingleton { get; set; }
  public object Instance { get; set; }
}

The
Registration object now has a Boolean flag to record if the registered type is to be treated as a singleton; the Instance property will be used to store a reference to the singleton when one is created.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public void Register<T, U>(bool isSingleton = false)
  where U : class
{
  var abstractType = typeof(T);
  var concreteType = typeof(U);

  var registration = new Registration()
  {
    AbstractType = abstractType,
    ConcreteType = concreteType,
    IsSingleton = isSingleton
  };

  _registrations.Add(registration);
}

Register() now accepts an optional parameter than indicates if the type is to be a singleton or not and this is assigned accordingly when the Registration object is created.

Resolution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private object Resolve(Type requestedType)
{
  var registration = GetRegistration(requestedType);

  object instance = null;
  if (registration != null)
  {
    instance = registration.Instance;

    if (instance == null)
    {
      var constructorParameters = ResolveConstructorDependencies(
        registration.ConcreteType);

      instance = Activator.CreateInstance(registration.ConcreteType, 
        constructorParameters.ToArray());

      if (registration.IsSingleton)
      {
        registration.Instance = instance;
      }
    }
  }

  return instance;
}

The requested type is instantiated in the same way as before (lines 12 through 16). A check is made to see if the type has been flagged as a singleton and if so a reference to this newly created instance is stored in the registration.Instance property before it is returned. This ties in with setting the return object to the registration.Instance (line 8) immediately after the Registration has been found and checking to see if it is null. If it is not null, it means the requested type is to be treated as a singleton and the stored reference should be returned.

In the next part of this series I will look at using method chaining to create a more readable syntax for registration.

A complete project containing all the source code for the container and a set of unit tests can be found here.