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…

Agile practitioners 2015

No comments

Thursday, January 29, 2015

I’ve just came back from the Agile practitioners conference. I enjoyed being part of the organizing team – it was fun giving a hand and helping to make this conference happen.
After attending an excellent “Lean problem solving” workshop by Claudio Perrone yesterday I was ready for a day of breakout sessions.
We've kick started the day with Angel Medinilla’s  “unicorns, krakens, self organizing teams and other mythological beasts” – it was about why self organizing teams do not happen automatically but can be built.
B8a_tw6CYAACefD
Also: Unicorns

Being the “Beginner” track lead I got to hear all of the lectures in that track – they were interesting and were not strictly beginner material.
B8bJrUoCIAA2RYCWe’ve started with “The missing lecture” by Uri Nativ (@unativ). It was an excellent talk about the things no one tells you when you start doing agile. Uri has explained how to successfully adopt agile by understanding how the development team perceive the change. He had excellent “do”" and don’t” and used examples from his own experience – good and bad.
Next was Oren Ellenbogen (@orenellenbogen) – “engineering your culture: how to keep your engineers happy” -  a talk on what great companies do in order to attract and retain great developers.
After lunch we had three “lightning talks” (15 min):
  • Gull Ben-Davind - “Why are QA members good scrum masters”, it was refreshing to see a presentation without any slides where Gull walked us through the way MyHeritage used QA/Testers as SCRUM mastersB8bvH7kCcAAZ7i1.
  • Ran Deri & Noam ZweigManaging technical debt in Cyberark. They explained how they managed to measure technical debt and then decide on what debt to pay on each team – while improvement as well. It was amazing seeing how an abstract idea (Technical debt) was measured using metrics and questioners and how they keep track of their debt on a daily basis.
  • The last lightning talk was by Barak Benjo who talked about “The 10 commandments of an agile tester in a legacy world”. Barak explained about how testers can be agile even when testing Legacy code and the kinds of tests that are available and how to choose what to do.
After the lightning talks we had an “Lean Lens” exercise/game with Andrea Darabos.IMG-20150128-WA0009
By using a fictional story we got to find all sort of “waste” in common scenarios during the software development process. You can read more about Lean Lens here – and download it and use it (creative commons) in your company.B8cD86FCIAEeoOo
Afterwards I got to give my talk on TDD – I hope that the code I showed (https://github.com/dhelper/DesignWIthTests) was not too much for the late afternoon hour.


And finally we got an excellent closing keynote by Claudio – where he briefly explained A3 method for problem solving and his brand new “popcorn board”.

It was a great conference and I got to talk to some interesting people and hear excellent talks – all in all a very good day.

10662187_10153582705419535_2271075304045224525_o

Happy Coding…

Azure IoT Hackathon

2 comments

Friday, January 16, 2015

Yesterday (technically today) I participated in an Microsoft Azure IoT Hackton at IronSource offices.

When I heard that several CodeValue consultants were asked to come and I knew I asked if I could tag along.

B7Y8SkYCUAAIfWu

Microsoft organized a great event – good venue, food (Pizza!) and very talented developers.

10915136_10152776995923768_4074683655461051494_nEach team had Raspberry PI (Model B+), Arduino (Yun) and/or Tessel and needed to create an innovative solution using an Azure backend – with not a lot of time to spare.

We CodeValuees got to meet talented and enthusiastic developers and to help them to utilize these new cool “IoT” devices. And let me tell you - my three years worth of high school electronics classes really helped.

We continued hacking until midnight then each team got to show what they’ve created:

  • an application that provides directions to the closest free toilet a.k.a “Smart bathrooms” (2Seek) B7bTIz2CQAEX3vZ
  • Dog tracker
  • parking spot finders (1st place)
  • and many more that I didn’t had a chance to see.
  • B7dBKibCEAAN23e (1)

In-between working with other teams we even managed to hack our own solution – meet the new CodeValue parking gate controller (Park-Value?) with permission management applications for the web, desktop, IOS and android:

IMG-20150116-WA0003

It was an awesome event – we got to write code in JS, Python, something that looks like C (Arduino) and even C# (actually only Ariel). We’ve played with several controllers and connect resistors to other components (did I mentioned high school electronics :-) ).

 

I definitely plan to continue hacking using Raspberry PI/Arduino/Tessel/<other> perhaps even blog about it.

 

Until then – Happy coding…

The four species of Agile

No comments

Tuesday, December 23, 2014

SukkotI’ve been a professional software developer since 2002 and worked for several software companies over the years - some practiced SCRUM, some used Kanban, some had a tailored made methodology and some didn’t have any methodology in place.

When starting with Agile a few years ago I found out that

“All waterfall companies are alike; each agile company is agile in its own way.”

Over the years I learnt to classify each company’s methodology using two factors:

  • Ceremonies – whether the company follows the methodology practices – iteration planning, retrospective, and/or daily standups.
  • Intent – does the company understand the agile values, strive for continuous improvement, quick feedback and embrace change (among other things).

And so I bring before you the four types of agile companies that I had the pleasure (in most cases) working for in the past:

Neither ceremonies nor intent (Aravah)

I got to work for several companies that had no visible software development process - or had a process which made no sense.

It doesn’t necessarily means that those companies didn’t had a project management “methodology” – in one case we had a whole division “planning” and “tracking” the various projects. Unfortunately the beautiful chats and predictions never affected us developers, and other than reporting (read: lying about) project hours it didn’t bother us much.

It was chaos incarnated – no one knew what was going on. Some of us were overworked while others would drink coffee all day. After finishing each task I had to ask my manager what to do next and from time to time we’ve shipped a product.

And so we’ve worked hard on fixing bugs and implementing new features without real understanding of the overall picture.

Ceremonies without intent (Hadass)

After a few years I got to work for Uber company Ltd. (if you know me you might know which company I‘m referring to). We’ve created a new shiny project that just had to succeed (at least until it got cancelled), and as such we needed to use the latest and greatest of everything - including a new methodology called SCRUM.

Consultants have been hired, courses have been taught, developers and managers were trained and a lot of money has been spent to make sure that the project would be a great success.

I was hired a few months after that and when I got there all that was left was the bills and a daily meeting that took between 30min to 1 hour – which for no particular reason we had to do while standing.

My educated guess is that the company refused to change its ways and so all that was left were the ceremonies: the daily meeting, planning that was done first by the team, then by managers and finally not at all and retrospective that happened three times during the year I worked there.

Intent without ceremonies (Lulav)

In one of the last companies I worked for before becoming a consultant was a team that knew about agile – the manager had experienced SCRUM before and wanted to us it to build software. He had a clear understanding of what he needed and wanted and how to achieve it. He had SCRUM custom made to fit his vision and while some of the benefits were lost on the way the underline values were always there.

Since the team was willing we were able to add daily meetings, retrospective and backlog and while the company never really wanted our iterations we were able to build a methodology very similar to ScrumBan that made sense for us.

We had TDD, task boards (plural) and clear priorities and we managed to create value for our customers – fast while reducing technical debt.

It was not always simple or easy but we all had the same goal and so were able to find tools and methodologies that worked for us.

Ceremonies and intent (Etrog)

This is where I became an agile addict – this utopian company decided to go with SCRUM and managed to stick to that decision.

When we noticed that SCRUM didn’t make sense for customer support – we’ve used Kanban for opened tickets.

After doing SCRUM by the book for more than a year we knew where we need to adjust our methodology and what we needed to keep on doing (retrospective) we’ve experimented with different iteration lengths, we had XP practices (pair programming, CI, TDD) and continuous deployment.

We managed to be productive and effective, we had management who was willing to provide us time to learn and much needed feedback.

Etrog_at_the_Market_of_the_4_Species_at_Bnei_BrakHadassim2

Summary

There you have it – four types of companies based on my (limited) experience – some were successful and some failed miserably.

If there is one thing I learnt is that you have to have intent and understanding in order to succeed with agile – I got to use agile in waterfall companies and I also so bad agile (and “no agile) practiced even when someone up the corporate chain decided that the company is an agile company – the decision rarely left the board meeting if the developers (read: those who write the code) were not on educated or in some cases even part of the process.

Take care when using comma in C++

No comments

Sunday, December 21, 2014

A friend had a weird bug while working in C++ last week. As sometimes it’s required he had to convert a string to an integer and instead of writing:
auto result = (SomeEnum) (stoi(s, nullptr, 10));
He wrote this:
auto result = (SomeEnum) (stoi(s, nullptr), 10);
Such a simple case of misplaced parenthesis caused the result to equal 10 instead of whatever s was.
In order to understand what the hell happened here you have to understand how the comma operator works in C++.
In C++ a comma is more than just a separator – it has its own rules and can cause grief if used incorrectly.
For example consider the following code:
auto whoami = ("111", nullptr, SomeFunc(), 42);
Can you tell what would the value be?
Strangely enough (or not) the result will be an integer “42”.
The reason for this strange behavior is that the comma operator works by evaluating each statement from right to left discarding the result other than the last one.
So keep in mind that SomeFunc was executed even if we didn’t get back its return value.
The same goes for the following (simpler) version:
int someInt = (1, 2, 3);
In this case someInt would equal 3.
And you can go complete crazy in a way only suitable for job interviews (from hell):
int someInt = (i = 100, i+= 20, --i);
In conclusion – be careful when using commas because you might not like what you’ll get.

Happy coding…

New Speaking engagement - DevWeek 2015

No comments

Monday, December 15, 2014

Now that I’m back from NDC London I have a chance to plan my upcoming speaking engagements – and it’s going to be a few busy months.
I’ve already blogged about my plans  for the next few months but since then I found out that I’ll be coming back to London (always a pleasure) in March for DevWeek.
image
The agenda looks amazing, good speakers and good talks and I’m happy to have three sessions – one for each day:

Navigating the TDD alphabet soup

TDD, BDD, ATDD are all methodologies that enable incremental design that is suitable for Agile environments. It seems that every day a new xDD methodology is born with the promise to be better than what came before. Should you use behavior-driven tests or plain old unit tests? Which methodology is better? And how exactly would it benefit the development life cycle?
In this session, we’ll sort out the various methodologies – explaining where they came from, the tools they use, and discussing how and when to use each one. Here we will once and for all answer the question as to whether or not there’s one “DD” to rule them all.

Battle of the .NET mocking frameworks

Writing unit tests is hard, isn’t it? You need an entire set of tools just to start. One of the crucial decisions when building this set is picking up a mocking framework. But BEWARE! What you choose has the ability to make you or break you! In this session, This talk will cover the capabilities and functionality of the leading frameworks, showing the good and the bad of the different options (both free and commercial), and making them battle to the death!

Unit testing patterns for concurrent code

Getting started with unit testing is not hard, the only problem is that most programs are more than a simple calculator with two parameters and a return value that is easy to verify. Writing unit tests for multi-threaded code is harder still. In this session, I will demonstrate useful patterns that he has discovered over the years, and that have helped him to test multi-threaded and asynchronous code and enabled the creation of deterministic, simple and robust unit tests. He will also point out the pitfalls to avoid.

Hope to see you there!

Unit testing concurrent code using custom TaskScheduler

1 comment

Sunday, November 23, 2014

Today I had a need to test an action that runs inside a Task:
public class ClassToTest
{
    private readonly IMessageBus _messageBus;
    private CancellationTokenSource _cancellationTokenSource;
    public event EventHandler OnNewMessage;

    public ClassToTest(IMessageBus messageBus)
    {
        _messageBus = messageBus;
    }

    public void Start()
    {
        _cancellationTokenSource = new CancellationTokenSource();
        Task.Run(() =>
        {
            var message = _messageBus.GetNextMessage();

            // Do work

            if (OnNewMessage != null)
            {
                OnNewMessage(this, EventArgs.Empty);
            }

        }, _cancellationTokenSource.Token);
    }

    public void Stop()
    {
        if (_cancellationTokenSource != null)
        {
            _cancellationTokenSource.Cancel();
            _cancellationTokenSource = null;
        }
    }
}
When faced with similar a code a developer has a “tiny” problem – how to force the code inside Task.Run to execute before the end of the test is reached.
And so we can write the following test that would fail - most of the times:
[TestMethod]
public void BadTest()
{
    var fakeMessageBus = A.Fake<IMessageBus>();
    var wasCalled = false;

    var cut = new ClassToTest(fakeMessageBus);
    cut.OnNewMessage += (sender, args) => wasCalled = true;

    cut.Start();

    Assert.IsTrue(wasCalled);
}

Why you should not use Thread.Sleep

The trivial fix would be to use Thread.Sleep (or similar Task.Delay) to make sure that the action would run before we reach the end of the test. Unfortunately adding this sleep will only cause the test would pass most of the times.
[TestMethod]
public void WorseTest()
{
    var fakeMessageBus = A.Fake&lt;IMessageBus&gt;();
    var wasCalled = false;

    var cut = new ClassToTest(fakeMessageBus);
    cut.OnNewMessage += (sender, args) =&gt; wasCalled = true;

    cut.Start();
    Thread.Sleep(1000);

    Assert.IsTrue(wasCalled);
}
The problem is that by adding a sleep we managed to achieve an inconsistent test while also making sure that the test would run a staggering 1 second – if that doesn’t sound like a lot think how much time 60 of such tests would run, what about 1000 tests each taking a single second?
In any case creating a test that could fail or pass inconsistently is a huge problem – it only takes a few such failures to convince your team to stop paying attention to that test – because it’s the test that always fail and soon enough they’ll stop paying attention to the continuous integration results and all of your tests would become useless (at least for alerting the team when a bug is introduced).

Creating a custom TaskScheduler

Looking for a solution I found a good post by Kjetil Klaussen where he suggests creating a new TaskScheduler that would cause the task to run in the same thread as the test thus causing the test to be predictable and simple:
public class CurrentThreadTaskScheduler : TaskScheduler
{
    protected override void QueueTask(Task task)
    {
        TryExecuteTask(task);
    }

    protected override bool TryExecuteTaskInline(
       Task task,
       bool taskWasPreviouslyQueued)
    {
        return TryExecuteTask(task);
    }

    protected override IEnumerable<Task> GetScheduledTasks()
    {
        return Enumerable.Empty<Task>();
    }

    public override int MaximumConcurrencyLevel { get { return 1; } }
}
Now we need to pass that scheduler to the executing task either by using a wrapper object or dependency injection.

Changing the current TaskScheduler

The problem is that you need to change your production code which is not always simple just like in my case where the action I needed to run was 5 calls deep and I didn’t want to pass the new TaskScheduler to each class on the calling stack.
I’ve started to look of a way to replace the current task scheduler.  Tamir D had a better idea - run the entire test inside a Task with CurrentThreadTaskScheduler.
Following his advice I’ve changed the Start method:
public void Start()
{
    _cancellationTokenSource = new CancellationTokenSource();
    Task.Factory.StartNew(() =>
    {
        var message = _messageBus.GetNextMessage();

        // Do work

        if (OnNewMessage != null)
        {
            OnNewMessage(this, EventArgs.Empty);
        }

    }, _cancellationTokenSource.Token, 
    TaskCreationOptions.None, 
    TaskScheduler.Current);
}
And now I could write the following test that would pass every single time.
[TestMethod]
public void GoodTest()
{
    var fakeMessageBus = A.Fake<IMessageBus>();
    var wasCalled = false;

    Task.Factory.StartNew(() =>
    {
        var cut = new ClassToTest(fakeMessageBus);
        cut.OnNewMessage += (sender, args) => wasCalled = true;

        cut.Start();
    }, CancellationToken.None, 
    TaskCreationOptions.None, 
    new CurrentThreadTaskScheduler());

    Assert.IsTrue(wasCalled);
}
Another benefit is that I could also test for negative conditions (something didn’t happen) since now all of the code runs synchronously.

Want to learn more?

There are many other ways to unit test concurrent code - if you’re interested in learning more ways to unit test concurrent code – I’ll be speaking about this topic at upcoming NDC London next week.

Until then - Happy coding…
Related Posts Plugin for WordPress, Blogger...
Top