Tuesday, 16 April 2013

TDD - The art of writing maintainable code

I was introduced to Test Driven Development (TDD) just over a year ago and I only wish I was introduced to it sooner. Like many other developers switching over to TDD, I had to undergo a complete shift in my thinking and approach to development -  it wasn't easy.

I am a programmer and believe it or not, nothing satisfies me more than jumping straight into the code and hacking away. But I found that as the code base grew, it became easier to break logic / features in other parts of the application. I believe this can send a developer into a spiral of paranoia, not wanting to dive into code and be bold in refactoring. This is not healthy and can quickly bring about unmanageable code.

We need something we can trust, something to give us reassurance - to be that child in the code playground, knowing that our parents are watching over us, making sure we don't hurt ourselves or set fire to the swing.

Good points

TDD allows us to keep our modules safe from the unexpected. If I modify a methods implementation then I want to be sure that the function still produces the same expected output when I inject certain arguments.

TDD also allows you to write awesome modularised code!

If you are writing unit-tests then ideally you should using TDD anyway. This means that you write your tests first so that you consider the design of your code.

For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 [TestMethod]
        public void RomanNumeral_8_Test()
        {
            // Arrange
            var expectedResult = "VIII";
            var number = 8;
            var converter = new NumberConverter();

            // Act
            var result = converter.ConvertToRomanNumeral(number);

            // Assert
            Assert.AreEqual(expectedResult, result);
        }


I take this as far as instantiating objects and invoking methods in my unit tests before I have even created these classes. BECAUSE THAT'S JUST HOW I ROLL! Then using a few shortcuts I can create implementation in moments. This allows me to think of code in abstract modules; I can design my program in classes and methods and spend time coming up with good names.

A few days later, I realise that I could have implemented the roman numeral conversion using a dictionary instead of writing multiple conditions. TDD gives me the safety net to carry out this change without worrying about whether I have broken a module. The change is shown below:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 public class NumberConverter
    {
        private Dictionary<int,string> romanMap = new Dictionary<int, string>();

        public NumberConverter()
        {
            romanMap.Add(1,"I");
            romanMap.Add(2, "II");
            romanMap.Add(3, "III");
            romanMap.Add(4, "IV");
            romanMap.Add(5, "V");
            romanMap.Add(6, "VI");
            romanMap.Add(7, "VII");
            romanMap.Add(8, "VIII");
            romanMap.Add(9, "IX");
        }

        public string ConvertToRomanNumeral(int number)
        {
            if (number >= 10 || number <= 0) return "";
            return romanMap[number];
        }
    }


If however you jump straight into the code (not thinking too much about modularisation) and write a set of classes which contain methods that have 30+ lines of code, then I am quite certain you will find difficulty in creating tests for this code. You will probably end up refactoring a few classes, breaking logic elsewhere and causing some serious trouble. Long story short - ALWAYS write your unit tests first.

Now that you have a completed set of unit tests for a dozen classes, You can be confident. You can dive into the code, refactor like a madman (or woman) and then run the unit tests to see if you have broken anything.

Bad(ish) points

However, TDD is not perfect and it does have it's problems. For example, you have written a large number of tests because you are a TDD boss and you have a large code base. However, for some reason you now need to undergo a large refactor. You do so and run the tests - 30 tests are now failing. Fixing these tests may take as long as the refactoring job itself and as a result it has doubled the amount of production time in producing this change.

Some see this as bad, however, I see it as a small price to pay for writing SUPER-MAINTAINABLE code! Plus, if you didn't have these tests, you probably would have decided against the refactor job in the first place.

Another problem with writing unit tests (if not done properly) is that you have a large set of tests that can take up to 5+ minutes to execute. This is bad. Tests should execute almost instantly. You will probably find yourself having to run these tests very often, probably every time you commit your code into source control.

Don't let your unit tests damage your productivity!

Overall

TDD is great! It enables you to consider the design of your code first, your code becomes very modularised as it needs to be in order to be testable and it ensures you don't break stuff.

However, TDD can eat into your productivity and slow you down. But I don't personally see this as a bad thing as we are writing super maintainable code that will ultimately save us time in the long run.

To sum up:

Good:

  • Keeps modules safe from unexpected changes.
  • Write modularised code.
  • Design your code first.

Bad:

  • Large refactor jobs may mean time spent fixing lots of tests.
  • If tests take long to run, it may slow you down.

Saturday, 13 April 2013

Minesweeper - Using recursion to reveal a region of mine-free squares

A few weekends ago, I thought I would tackle an infamous code dojo problem - the dreaded minesweeper.

We all know it. The idea is simple, we reveal a grid whilst avoiding the mines that lay hidden beneath.

The reason why I decided to blog about this is because it's not every day that I find a scenario to use recursion, but it is however well suited for this problem.

Recursion is when a method calls itself and is used for solving many computational problems, especially in games. In this article, I am technically not having a method call itself, but a form of recursion is happening.

Please note: When I mention a square, cell or coordinate, just consider them as a square on the grid. Knowing the exact difference here is not required to appreciate what I am doing with recursion :) 

Problem

A common problem which may cause a sweat or two (or none) for a developer is the revealing of the mine-free squares.

This occurs when you select a square which reveals a region of mine-free squares until it reaches a square that is connected to a mine. This is what the green squares are in the image below:


(Actual in-game footage!!)

I built this game using C#, WPF with Net Framework 4.

Solution

I decided to use the magic that is recursion for solving this problem.

The method below is what is invoked when a square has been clicked. The implementation then goes through a process of invoking 'RevealNextCell' for each surrounding square.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
 internal void Reveal(int x, int y)
        {
            RevealNextCell(x - 1, y - 1);
            RevealNextCell(x - 1, y);
            RevealNextCell(x - 1, y + 1);
            RevealNextCell(x + 1, y);

            RevealNextCell(x, y - 1);
            RevealNextCell(x, y + 1);
            RevealNextCell(x + 1, y - 1);
            RevealNextCell(x + 1, y + 1);
        }

The 'RevealNextCell'  begins by fetching the coordinate (square) and checking that it is a valid cell to be processed and if it isn't we return on the method - When using recursion it is important to not forget your return conditions or you may get into trouble.

'IsBlank' checks the mine counter on the coordinate (The counter is set when the mine field is first created) to determine whether it is a mine-free square or not. If so, it sets the colour of the cell (Yes, this shouldn't be hard coded!) and finally invokes 'Reveal' which will got through the process of checking all the surrounding squares of this cell.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
        private void RevealNextCell(int x, int y)
        {
            var coordinate = GetCoordinate(x, y, mappedCoordinates);
            if (coordinate == null) return;
            if (coordinate.State == State.Revealed) return;

            if (IsBlank(coordinate))
            {
                coordinate.State = State.Revealed;
                coordinates[x, y].Cell.Background = Brushes.LightGreen;
                Reveal(x, y);
            }
            else
            { 
                coordinate.State = State.Revealed;
                coordinates[x, y].Cell.Child = new TextBlock() { Text = coordinate.Counter.ToString() };
                coordinates[x, y].Cell.Background = Brushes.Goldenrod;
            }

        }


To conclude, recursion is a great technique for solving many game problems and can save you from writing nasty nested loops which are unreadable. Recursion can however be dangerous and you may end up writing infinite recursion - just be sure to write that return condition!

Also, you may be at risk of stack overflow if you use deep recursion so be cautious when using it but in the case of a simple 20 x 20 minesweeper grid; it works like a charm and it keeps your code clean and easy to read.

Happy mining!