TDD is like riding a bicycle

No comments

Thursday, May 14, 2015

From time to time I get to teach unit testing and TDD to developers. And every single time I get to learn something new.
During such class we got to the part where I talk about TDD. When I’ve explained about writing tests before code as a design activity - nobody objected. When we did step by step FizzBuzz kata together – everything was just rainbows and unicorns. Since the class seemed to grasp the concept of TDD I’ve decided to get their hands dirty with another TDD exercise – to do on their own (pair programming style) – and all hell broke loose… Actually it was fine, but obviously harder for the students. Some did better than others, keep in mind that it was the end of (a very long) day, it was the first time they ever attempted TDD and remember that these guys only found out about unit testing that same morning.
I did get very interesting results – as well as comments from the class.
After writing a few tests (doing TDD) one guy looked at me and said: “This is quite a lot of work, I think I can solve the problem faster without any unit tests...” I told him to try, but it made me think TDD and learning new skills. Any new skill requires practice in order to master it – think playing guitar, juggling or the ability to sleep late regardless of the amount of noise in your house (and an angry spouse trying to wake you up). In the beginning it’s hard and feels like a lot of effort for little gain and as time, as you improve it becomes easier and easier until one day you might become so good in what you do – it actually look easy to someone looking from the side.
Timageo me it reminded learning to ride a bicycle – at first you might have trouble making the wheels turn, in this point you’ll probably move faster (and get where you want to go) without the bike (a.k.a walking) - just like the guy in my class – in this point he has better chance to solve his problem without TDD (with or without bugs). The next step is learning how to make semi-trusty vehicle stop, again doing what you did until now is the simplest possible solution – just put your legs down! But if you persist you learn that using brakes is better. After some time your brain translates “I need to stop” to whatever you need to do in order to make your bike stop.
As you get better in making your new mode of transportation go where you want to go it becomes easier and easier until one day you notice that you no longer think about the actual operation of riding the bicycles – you just do it. In that point it’s quicker to use your trusty (hello kitty pink?) bicycle to get wherever you need to be. At this stage you discover that you prefer riding your bike as oppose to the old way of “walking there”.
Same goes for TDD – in the beginning it might be hard and even seems like a waste of time – time you could have used to do something better (drink more coffee?) but as you progress you might find that it saves you time until one day you find out that it’s the way your brain solves design problems – automatically.
There is another aspect in which TDD is similar to riding bike:
Life is like riding a bicycle. To keep your balance, you must keep moving.
Albert Einstein
Just like one of the smartest guys ever lived said – you need to keep moving if you want to avoid falling – which also reminded me of the Red-Green cycle – if you want it to succeed you have to keep short, quick iterations and try to avoid making too many stops along the way – but that’s a subject for another blog post.

Until then – Happy coding…

AssertHelper V1 released

No comments

Friday, April 24, 2015

Exactly one year and four months passed since my first try at fixing the state of asserts in NUnit. You can read all about it in my post – One assert to rule them all.
My intent was to create one assert that would automatically choose the right way to check test result (I didn’t invet the idea but the old project has been discontinued).
Since the initial release I’ve used AssertHelper on several occasions (projects), taking requests and adding support along the way. Finally AssertHelper V1 is ready to be tested in the real world.
I’ve added MSTest support and a last minute entry – print the “offending” lambda that caused the assert to fail.
image
So why don’t you give it a try - AssertHelper is available via NuGet (Install-Package AssertHelper).

And please let me know what you think.

I’m a software developer - not a lawyer

No comments

Wednesday, April 15, 2015

61101315A long time ago not that far away I’ve been hired by Omni-Corp to work on the new and shiny product. We had talent, budget and cool technology on our side, and that project was going to crash and burn (and ultimately cancelled) in less than a year.
Nobody’s perfect - we had our share of problems, some technical and some not. One of which was the way that requirements were managed:
The product guy (or gal) would create a word document describing a new feature. A few meetings would happen and when development agree on the specifics of that feature coding would begin. Lastly testers would use the word document to create test plans and validate that the requirements were met.
It was a good process, easy to explain (and follow) with clear stages (Requirements –> Development –> Testing), and clear outcome of each stage.
Like all best laid plans – this one did not survive its meet-up with the real world.
Since the product persons were “business people” and not “software developers” they did not fully understand the logical way in which developers understood the requirements and since developers were being “developers” we tended to come up with our own solutions whenever we met a “logic hole” in the requirements document.

And mistrust and chaos would follow…

We (devs) would claim that since it was not in the document we had to implement was we saw fit – and so a young bright manager came with the solution: quickly update the document five minutes before a meeting and then point it out that “it was definitely in the document!”.
Now we had a new problem – it was impossible to write software with a constantly changing requirements and so the “requirement freeze” came to be.

Requirement freeze!?

As you might have guessed at a specific point in time the requirement document would be locked and cannot be updated again, and just like code freeze – it didn’t last. Once a product guy discovered that he can make a copy of the frozen document, update it and link to it.
At his point it was just ridicules as well and counterproductive – mistrust grow as both teams felt that the other team is trying to cheat them. The development team felt that product was trying to shove half baked, constantly changing features while the product team felt as if the developers were always on the lookout for new excuses to avoid work.
And so every single stage in the process felt as negotiation between opposite sides – I got to a point where I refused to sign on requirements before reading them several times and then asking my boss to read them to make sure that they were complete and did not contain any hidden conditions.
I felt like a lawyer! There’s nothing wrong in being a lawyer (some of my best friends are lawyers) as long as it’s in your job description.

And it was all our fault

We (both teams) forgot that it was our job to create software according to the demands of our customers.
Looking back at that time I realized something – requirements change, even in a perfect project customers tend to change their minds, bugs are fixed and new data can cause us to look at our product differently. I got to work for many companies before and since and not once did I meet the mythical 100% true never changing requirements project – even with the best of the best.
We were fighting reality – where projects tend to change over time. If only we’ve used the same passion and energy to make sure that we could change our code as easily.
The truth is that it should be easy to change your code. Refactoring, unit testing, code reviews and other software development best practices can help you get there and as good, experienced software developers it was our job to use the right practices in order to provide our customers with new features and bug fixes as quickly as possible – instead of complaining about the fact that requirements always changed…
It can be very hard to make changes in large complicated code bases. When we make changes it's important to know that we are making them one at a time. Too often we think we are changing only one thing but instead we end up changing other things unintentionally: we end up introducing bugs.
Michael Feathers – working effectively with legacy code
It’s as simple as that – simple code equals easy to change. So make sure you’re doing your job before trying to change the world.

Happy (& clean) coding…

Electronics 101 - Getting started with Arduino

No comments

Wednesday, April 01, 2015

ArduinoYunFront_2_450pxThese days everybody talks about IoT. Connecting your toaster to the internet has become a nationwide priority. Finally the barrier to entry to the hobbyist/home electronics have fallen and anyone can hack an hardware solution using cheap and simple components.
And putting together a simple circuit controlled by Arduino/Raspberry Pi/whatever is easy, it’s just a matter of
I have always enjoyed writing software that effect the real world and this new wave seemed like a good opportunity to dust off my 12th grade electronics classes from old. Having acquired an Arduino Yun I’m ready to create my very own “hello world” example. In this case make a LED (Light Emitting Diode) blink.

Ingredients

For the purpose of this simple demo you would need to following:
image
  • Arduino software – download from http://arduino.cc/en/Main/Software, install and you’re ready to go.
  • Arduino - I’m using Arduino Yun but for the purpose of this demo any Arduino will do.
  • Breadboard – this nifty “board” would hold the components in place. This enable us to connect components without soldering stuff together. It has a bunch of holes in it with “wires” connecting the holes to one another.
    IMG_20150330_103459
    The idea is that all the components at the same row are connected to one another. Just make sure that you do not “cross the streams” – each component has at least two leads and they (usually) need to be connected to different rows.
  • LED (pick a color, any color)
    image
    The star of this demo – lights up when current passes through it. you might have noticed that our friend here has two leads one longer than the other. The longer one is the positive one and should be connected to where the current comes from the other shorter lead should connect to the ground.
  • Resistor
    Since we don’t want to burn the LED we need to add a resistor to the mix.
    image      
    It has a bunch of lines on it with pretty colors. Those tell us what is the resistor’s resistance, but don’t worry about it just yet. In this case I’ve used a 1K resistor.
  • 2 wires – to connect stuff together.

Writing the application

Writing code for Arduino is easy. A program is called “sketch” and it uses a C like syntax. We have comments, variables and functions. The bare minimum are two methods: setup and loop.
  • void setup() runs once and this is where you add your initialization logic
  • void loop() runs continuously – this is where the program logic should be written.
You can add additional methods if the need arise but this is as simple as it gets.
image
Let’s write our program. We’ll use pin 13 for output. The reason for choosing pin 13 is that on most Arduino boards we have a LED on board.
yun_scheme_p3
The code for this first simple program looks something like this:

const int ledPin = 13; 

void setup() { 
    pinMode(ledPin, OUTPUT); 


void loop() { 
    digitalWrite(ledPin, HIGH); 
    delay(1000); 
    digitalWrite(ledPin, LOW); 
    delay(1000); 
}

Seems simple enough, but just in case let’s go over the code:
  • The first line declare a constant value which we’re going to use as the output pin
  • In the setup method we initialize that pin as an output pin
  • The loop would start with setting pin 13 to HIGH which supplied 5 volts to that pin –> LED light goes on
  • Delay for a second (1000ms) so that we’ll be able to see the pin light
  • Set pin 13 to 0 volts (LOW) –> LED is off
  • Another Delay
And that’s it, the loop would run continuously turning the LED on and off.
Use Ctrl+R to compile and verify the sketch. You can also upload and run without connecting any components and see the little L13 LED on the board light up – but what’s the fun in that?

Connecting the board

Looking at the Arduino you’ll see it has a few numbers and weird words on its side.
image
The numbers are the digital inputs/outputs. near number 13 we have GND (ground) which will also need.
Connecting to the outputs is as simple as putting a wire through a hole.
  • Since we’re used 13 as the output we’ll connect one wire to 13. The other wire will be connected to GND.
  • Connect the first wire to the resistor
  • Connect the resistor to the LEDs longer lead
  • Connect the short lead to the wire that goes back to GND (ground).

In the real world it would look something like this:
image
For the uninitiated it might look a bit “wireless” – the components do not appear to be connected. Just remember that the bread board has wires running underneath which essentially connect the whole line.
Here is the same circuit with the “hidden connections” marked.
image

Run!

Connect your Arduino to your computer and Upload the sketch.
image
Note: Don’t forget to choose the correct port and board before trying to upload.
image
And after a short while you should see the LED lighting up!

image

Troubleshooting: If your LED does not light up (but the on-board LED does)check that all the components are connected in the right order, make sure that you’ve connected the positive side of the LED (long) to pin 13 and the negative side to GND.
If you feel comfortable enough with this simple example – why not try and implement a binary counter:

What’s next

That was a simple electric circuit using Arduino Yun. I hope that it looked simple enough and that you’ll be able to use this post to build your own. I hate to see software developers shy from electronics just because it’s out of their comfort zone (being “hardware”).
As for me – I’m waiting for a big shipment of electronic goodies – and have plans for future hobby projects that I can use them in. I might even write a few more posts on the subject.

But until then – happy coding…

Visual Studio tip: paste json/xml file as class

1 comment

Monday, March 09, 2015

I’m a long time listener of .NET rocks and today during my drive to work while listening to TDD on .NET and Java with Paul Mooney, Carl mentioned a cool tip I want to share with you.
In the past I have use XSD.exe to create classes from XML files for serialization purposes (and similar tools for json) but no more.
Using Edit –> paste special (which I didn’t even knew existed until today) you can create C# (or VB.NET) classes from
image
You can copy an XML file to the clipboard and and so the following file:
<?xml version="1.0" encoding="UTF-8" ?>
<Data>
    <Series>
        <seriesid>273690</seriesid>
        <language>en</language>
        <SeriesName>Constantine</SeriesName>
        <banner>graphical/273690-g2.jpg</banner>
        <Overview>A man struggling with his faith is haunted by the sins of his past but is suddenly thrust into the role of defending humanity from the gathering forces of darkness.</Overview>
        <FirstAired>2014-10-24</FirstAired>
        <Network>NBC</Network>
        <IMDB_ID>tt3489184</IMDB_ID>
        <zap2it_id>EP01921172</zap2it_id>
        <id>273690</id>
    </Series>
</Data>
Will become this class(es):
image
And it would also work for json files as well.
It’s not perfect, I found that I needed to “re-copy” the source after each use and the “paste as xml classes” option will only appear for .NET 4.5 (and above).
No more using external tools to get serialization up and running – a big time saver.

Happy coding…

Catch - multi-paradigm automated test framework for C++

No comments

Wednesday, March 04, 2015

catch-logo-smallWhen unit testing in C++ I tend to use Google Test/Mock, it’s simple to use, multi-platform solution. In the last few days I have been having second thoughts about it due to a new framework called Catch.

What is (the) Catch?

“Catch” stand for C++ Automated Test Cases in Headers. It’s an open source project (GitHubbed). What I like about it is that instead of implementing the old and trusted “[A..Z]Unit” way its creators have decided to rethink the way tests are written - with a few small changes that make a difference (more on that later).
Getting started with Catch is done by downloading catch.hpp and that’s it - you’re all set to go, no need for linking with a dll/lib which can be quite painful when working in C++ (where you sometimes need a different library for each release/debug, platform, single/multi-thread and day of the week).
But this quick & simple way to get you up and running is not the reason I find myself liking Catch – it’s the way the tests are written.

Taking it for a spin

I’ve wanted to try Catch and see how it rolls. For that I’ve decided on implementing the Bowling kata (if you don’t know what it is – go read about it, I’ll wait).
Writing the first test was simple and looked very similar to the tests of old:
TEST_CASE(Score_NewGameCreated_ScoreIsZero)
{
    Game game;
    int result = game.Score();

    REQUIRE(result == 0);
}
Noting big here – or is it? Have you noticed something different about my assert?
Catch has done something that the unit testing world should have done a long time ago – use code to describe what assert is needed instead of dozens of Assert.X methods (in fact I’ve been doing the same for .NET). When running the test I was pleasantly surprised to find the following error message:

image

See that – it tells me exactly what went wrong: I have a variable called result which does not equal ‘0’, in fact it’s ‘-1’. With test failures like this I can understand what went wrong – even without debugging my test.
I’ve wanted to see if I can get even better error message from Catch and so I moved the call to the method into the REQUIRE block and got the following error:
image
Even better – now I can really understand what’s going on – Game.Score did is not zero.
I’ve continued my TDD experience and then I found the 2nd feature that makes Catch standout – Sections.
Usually I have a hard time with developers (ab)using Setup methods. I’ve wrote (read: ranted) about this before.
In a nutshell – I do not like setup methods because:
  • After a while the setup method becomes hard to understand and tend to initialize fields that are only needed in some of the tests.
  • It’s hard to fully understand a test that is split between two places (setup and actual test method)
  • As an added bonus you also get shared state (fields again) that can (read: will) cause a lot of damage in the future (test A fail when run after test B)
And so I was happy to find out that Catch has initialization per test case and the actual tests are written in isolated sections:

TEST_CASE("Simple Bowling score -- without score or strike", "[BowlingKata]")
{
    Game game;

    REQUIRE(game.Score() == 0);

    SECTION("All rolls are gutter balls --> score == 0"){
        RollSeveral(game, 20, 0);

        REQUIRE(game.Score() == 0);
    }

    SECTION("All rolls are 1 --> score == 20"){
        RollSeveral(game, 20, 1);

        REQUIRE(game.Score() == 20);
    }

    SECTION("All rolls are 2 --> score == 40"){
        RollSeveral(game, 20, 2);

        REQUIRE(game.Score() == 40);
    }
}
not sure if I like the fact that I’m also asserting something about the initial state of the tests – seems a very un-AAA thing to do and it confuses the hack out of the test results (says it has 2 X 3 == 6 assertions) so I’ll remove it (and create a test just for this scenario).
When I first saw similar code in the tutorial I almost decided not to try Catch at all – it seems like pouring code instead of writing atomic, isolated tests. In order to really appreciate what Catch does I’ll make one of the tests fail:
image
We’re looking at three different tests - which means that if one of the sections fails – it does not effect the other two. This ability enable us to write common code in the beginning of the test case and then write different sections for each test (case?).
Have you noticed another cool feature on the way? The “tests” names are simple texts – we’re getting to a point in which naming a method with underscores and language trickeries will become obsolete.
imageimage

Catching a case of BDD

Using macros Catch also cater to the BDD crowd, I’ve decided to write the rest of the tests using BDD style:
SCENARIO("If on his first try in the frame he knocks down all the pins, this is called a strike. His turn is over, and his score for the frame is ten plus the simple total of the pins knocked down in his next two rolls.")
{
    GIVEN("Bowled strike on first turn")
    {
        Game game;
        game.Roll(10);

        WHEN("All rest rolls are gutter balls")
        {
            RollSeveral(game, 18, 0);
            THEN("Total score is 10")
            {
                REQUIRE(game.Score() == 10);
            }
        }

        WHEN("Next two rolls are not spare or strike")
        {
            game.Roll(3);
            game.Roll(4);
            RollSeveral(game, 16, 0);

            THEN("Total score is 10 plus twice the sum of these rolls")
            {
                REQUIRE(game.Score() == 24);
            }
        }        
    }
}
Again We have a common GIVEN step and two isolated When-Then clauses. When one of the behaviors fails we get a nice BDD style error message:
image

Conclusion

You might have noticed that I like Catch – but it’s not all a garden of roses. I miss having parameterized tests which I need for several of my projects and currently there is no Visual Studio test runner to be seen both of which are a deal breaker for some of the projects I’m involved with.
Since it’s open source there’s a chance that we’ll get an implementation for it in the future.
I know I want to use Catch as much as I can because of features such as sections, test “names”, one assert (require) and error messages.

Happy coding…

FizzBuzz TDD kata– using Reactive Extensions

2 comments

Wednesday, February 04, 2015

I was thinking about Reactive extensions (and using it) and then it hit me – why not try and use Reactive Extensions (Rx) in order to perform the FizzBuzz kata – it seems like a perfect fit.
And so I set myself to try and use only Rx when performing this TDD kata.

What is this FizzBuzz – a quick introduction

Fizz buzz is a group word game for children to teach them about division.[1] Players take turns to count incrementally, replacing any number divisible by three with the word "fizz", and any number divisible by five with the word "buzz".
[Wikipedia] The idea behind this exercise is to solve the simple problem of writing the numbers from 1 to N according to the following three rules:
  1. Number is divisible by 3 –> write Fizz
  2. Number is divisible by 5 –> write Buzz
  3. Number is divisible by 3 and 5 –> write FizzBuzz
  4. Otherwise write number
It’s a simple problem to solve – in fact I’m sure you’re already solving it in your head. But don’t start just yet, one of the important aspect of TDD is to only concentrate on a specific problem each time and don’t design the whole solution up front.

My First test

I generally start with the simplest wrong input I can think about. I do this as a form of “warm up” to begin my test-code cycle.
In this case any input which is lower then 1 should return an empty string.
[Test]
public void GivenNumberBelowOne_ReturnEmptyString()
{
    var result = FizzBuzz.Generate(-1);
 
    Assert.That(result, Is.Empty);
}

I wrote the simplest test, although some would claim that I should have used a negative number instead of ‘0’ – which would work for me as well. If you feel the test is inadequate – feel free to add another test as soon as you write the code to make this simple case pass
I run the test – and it failed (no surprises here).
Now to write the minimal amount of code to make the test pass:
public static string Generate(int max)
{
    return string.Empty;    
}
As simple as that.
To some my implementation would look like cheating (especially if you do not have any previous TDD experience). But when you think about it you realize that the code above elegantly fulfills all requirements (in this point and time).

Let’s make it more interesting

Now that we got that out of the way it’s time to start adding some value to our code.
The next requirement to  tackle is “unless the number is divided by 3 or 5 we should just write it”.
So the simplest test here should be using 1:
[Test]
public void Given1_Return1()
{
    var result = FizzBuzz.Generate(1);

    Assert.That(result, Is.EqualTo("1,"));
}

To make the test pass I can write the following – trivial code:
public static string Generate(int max)
{
    if (max < 1)
    {
        return string.Empty;
    }

    return "1,";
}

Now let’s see what happen if we pass ‘2’ (code + test):
[Test]
public void Given2_Return12()
{
    var result = FizzBuzz.Generate(2);

    Assert.That(result, Is.EqualTo("1,2,"));
}

// Code
public static string Generate(int max)
{
    if (max < 1)
    {
        return string.Empty;
    }

    if (max == 1)
    {
        return "1,";
    }

    return "1,2,";
}

Now we get to the 3rd stage of the TDD cycle – refactoring and since I wanted to use Rx I refactored the code accordingly:
public static string Generate(int max)
{
    var result = string.Empty;

    if (max > 0)
    {
        Observable.Range(1, max)
            .Subscribe(i => result += i + ",");
    }

    return result;
}

the code above is basically a simple foreach using Rx:
  1. Create an observable that would return a range from 1 to max

  2. Subscribe (iterate) the observable and add each item to the result
Refactoring is not only for my “production code” and since both tests are use similar code I can refactor my tests using NUnit’s TestCase:

[Test]
public void GivenNumberBelowOne_ReturnEmptyString()
{
    var result = FizzBuzz.Generate(0);

    Assert.That(result, Is.Empty);
}

[TestCase(1, Result = "1,")]
[TestCase(2, Result = "1,2,")]
public string GivenNumberUpTo2_ReturnNumbers(int input)
{
    return FizzBuzz.Generate(input);
}

Although I could also test the 1st requirement (less then 1) using the same code I prefer to separate them since they are logically belong to different aspects of my solution. In other words I prefer to “pay” the (low) maintainability price in order to separate the requirements (readability).

Onward to Fizz

Now we’re finally getting somewhere – let’s write a failing test for “3”:
[Test]
public void GivenNumberDividedByThree_ReturnFizzInstead()
{
    var result = FizzBuzz.Generate(3);

    Assert.AreEqual("1,2,Fizz,", result);
}
Since we’re already familiar with TDD I’ll allow myself to jump a few stages (in this post, not in the actual Kata) and show you the result after refactoring – the code starts to look better – Rx style
public static string Generate(int max)
{
    var result = string.Empty;

    if (max > 0)
    {
        IObservable observable = Observable.Range(1, max);

        observable
            .Where(i => i % 3 != 0)
            .Subscribe(i => result += i + ",");

        observable
            .Where(i => i % 3 == 0)
            .Subscribe(i => result += "Fizz,");
    }

    return result;
}

The end result

In a similar matter I’ve TDD’ed my way to Buzz & FizzBuzz and got the following code:
public static string Generate(int max)
{
    var result = string.Empty;
    if (max <= 0)
    {
        return result;
    }

    var observable = Observable.Range(1, max);

    var dividedByThree = observable
        .Where(i => i % 3 == 0)
        .Select(_ => "Fizz");

    var dividedByFive = observable
        .Where(i => i % 5 == 0)
        .Select(_ => "Buzz");

    var simpleNumbers = observable
       .Where(i => i % 3 != 0 && i % 5 != 0)
       .Select(i => i.ToString());

    var commaDelimiter = observable.Select(_ => ",");

    IObservable specialCases = (dividedByThree).Merge(dividedByFive);
    simpleNumbers
        .Merge(specialCases)
        .Merge(commaDelimiter)
        .Subscribe(s => result += s);

    return result;
}
I found a cool thing – as soon as I handled numbers that divide by 3 and 5 separately I “automatically” got the case of FizzBuzz.
That’s it – simple and elegant and with Reactive extensions. Unfortunatly I failed creating an Rx only solution (I still check for i < 0)
And the all exercise took a few minutes (more time than it took me to write this blog post).
Happy coding…
Related Posts Plugin for WordPress, Blogger...
Top