The problem with clients…

30 11 2010

Actually I kind of like having them, but unfortunetly it means deadlines and that also usually means crazy ass debugging sessions, so the
third TDD session will have to wait till tomorrow night…! 😀

“…ten li po ta’mikrofon!…”

Advertisements




Timer – Part 1

27 11 2010

Why part 1? Because arrays are zero-indexed for me.
Lame jokes aside, let’s continue… um… now what?

In the army when we’ve done navigation field exercises they told us that whenever we get confused or lost the best option is to find higher grounds and survey the land. This particular advice is just as relevent for me here as it was back then [although no matter how many times I got up I always got lost again on the way down but that’s another story :D].

The equivalent to taking to the higher grounds here is looking back at the original answer to “what do I want?”. Ok, looked at it, now what’s the simplest state in which a Timer object can exist? The simple answer [and simple is the only answer one should look for when testing first] is a Timer that isn’t running. Sounds good, let’s do that. I can already see that I’m going to end up with some duplicated setup code so I’ll write the fixture code now [but keep the previous test in a different file, call this one timer_not_running_tests.cpp].

#include <UnitTests.h>
#include "Timer.h"

struct timer_not_running
{
  Timer::name_type _name;
   Timer _timer;

 ~timer_not_running(){}
    timer_not_running()
    : _name("NotRunning")
    , _timer(_name)
    {}
};

TEST_FIXTURE(timer_not_running, _check_timer_name_is_correct)
{
  CHECK_EQUAL(_name, _timer.Name());
}

Compile, run and watch it flame. Why? Timer::Name() returns a constant string to satisfy the previous test. Stop, let’s reflect here for a second before going on. If we look at the code from last post we’ll also notice that the first test we wrote suffers from a bad case of code duplication. The “Timer1” string is constantly duplicated, in the test and in the Timer class code. I’m going to take the time now to remove the duplication by refactoring the Name() function.

#ifndef _TDD_TIMER_
#define _TDD_TIMER_

class Timer
{
  public:
    typedef char* name_type;

    name_type Name() const { return _name; }

    Timer(name_type name)
    : _name(name)
    {}

  private:
    name_type _name;
};

#endif/*_TDD_TIMER_*/

Compile, run and watch both tests pass. What have I learnt? Removing code duplication as soon as possible leads to more general solutions. So from now on, obvious code duplication should be removed as soon as possible. The second test should always be written though, to verify that the solution is indeed what we want. The other approach for something like this is using the additional tests to force the functionality to change, in this case I would have had to hold the name string in an actual variable in order to have different names. Using more tests to zoom-in on the correct implementation is called Triangulation within the Agile circles and I usually use it to flesh out complex functionality. Alright, less talk more code, I’m testing a timer that isn’t running. If a timer isn’t running then the total time that it counted should be zero, right? let’s test.

TEST_FIXTURE(timer_not_running, _check_total_elapsed_time_is_zero)
{
  CHECK_EQUAL(0, _timer.TotalElapsed());
}

Compile, run, things explode, let’s add the right function.

#ifndef _TDD_TIMER_
#define _TDD_TIMER_

class Timer
{
  public:
    typedef char* name_type;
    typedef double elapsed_type;

    name_type Name() const { return _name; }
    elapsed_type TotalElapsed() const { return 0; }

    Timer(name_type name)
    : _name(name)
    {}

  private:
    name_type _name;
};

#endif/*_TDD_TIMER_*/

Whoops, code duplication. Let’s refactor.

#ifndef _TDD_TIMER_
#define _TDD_TIMER_

class Timer
{
  public:
    typedef char* name_type;
    typedef double elapsed_type;

    name_type Name() const { return _name; }
    elapsed_type TotalElapsed() const { return _totalElapsed; }

    Timer(name_type name)
    : _name(name)
    , _totalElapsed(0)
    {}

  private:
    name_type _name;
    elapsed_type _totalElapsed;
};

#endif/*_TDD_TIMER_*/

Compile, run, all tests pass and I’m happy. The code itself isn’t very exciting to look at, after all of this and I’ve just got two functions up and running. But the bigger picture is a bit more invloved. I’ve learnt the importance of removing code duplication early, I’ve had some more practice in making assumptions about functionality [a timer counts the total elapsed time therefore a timer that isn’t running should have a zero value for it]. And last but far from least, I’ve started documenting the contract between the client [what is needed] and the developer [what the code does] through the tests; that is, the timer must have a name and will measure a total amount of elapsed time. There is one more design decision I’ve made here, it might not be as obvious though, can anyone spot what it is??

“…Into the half light, Another velvet morning for me, yeah…”





Need…More..Time

26 11 2010

What a hectic, horrible week… Sometimes life throws a curve ball that hits you square in the, well, soft bits…
But enough bad sport-to-life metaphors; let’s get on with some code. Been writing alot of C# lately and I’ve got lots of stuff to say about the language [and most of it is even good believe it or not] but right now I’d like to take the time to go through the motion of TDD and my Timer class and all in glorious C++, yay!

For my main testing framework I use UnitTest++ which is simple to use and robust testing framework by Noel Llopis and Charles Nicholson. The only hickups I’ve had with it so far are the ++ in the namespace name and the fact that the TEST_FIXTURE macro seems to generate an intellisense error on odd numbers of tests [which is most likely a problem with the intellisense on my copy of Visual Studio 2010 Express rather than the actual code].

Most of the time when I’m about to test or design something the first question I usually ask myself is, what do I want?
So, in short, I want a class that will be able to act as a timer and measure both its total running time and the elapsed time between two ticks [handy for frame timing]. Like a good stopwatch it should also be able to stop, start and reset when needed.

Ok, I know what I want, let’s see what I can get. In a glance I can also see that as far as a full component the Timer isn’t going to be overly complex so I most definitly can finish writing it up it a while and a little bit… But because I’m not sure where all the bits are going to go and the whole point is to practice TDD I’m going to test first and see what happens.

Everything set, everything go. First test.

#include <UnitTest.h>
#include "Timer.h"

TEST(check_timer_name_is_timer1)
{
  Timer timer("timer1");
  CHECK_EQUAL("timer1", timer.Name());
}

Stop, compile, and watch it crash. So many things don’t even exist yet. Before I continue though, most developers I worked with would probably laugh at the level of functionality I’ve just tested. The arguments I usually hear are: It’s too small, it’s testing that the language work and it’s such a small thing it’ll only take a second to write. And to that I usually answer, there’s nothing too small to test because you never know what you might change. Also, I’m not actually testing functionality, I’m designing it. And finally, if it only takes a second to write it’ll only take a second to test and surely it’s better to have a test then not have one.

Now what?
Well, the compiler tells me that I don’t have a file called “timer.h”; so let’s create one.
Now the compiler complains that there’s no such thing as a Timer class. Quick, let’s write one up.

#ifndef _TDD_TIMER_
#define _TDD_TIMER_

class Timer
{

};

#endif/*_TDD_TIMER_*/

Compile, run, more complaints… What a fussy environment. The constructor signature doesn’t match and there’s no function called Name().

#ifndef _TDD_TIMER_
#define _TDD_TIMER_

class Timer
{
  public:
    typedef char* name_type;
    
    name_type Name() const { return "timer1"; }

    Timer(name_type name){}
};

#endif/*_TDD_TIMER_*/

Compile, run and phew… The test passes. The first functionality is in. It doesn’t look like much but the important thing is that it follows the design decisions as documented via the tests. I think this process is far too long for any single post and I’ll run it over the next few days [one post per day] until I get a timer or a headache, depends.

“…and if I bring a little music I can fit right in…”





17 11 2010

Seeing as how my head is not into programming this week due to a family emergency on the weekend and the ongoing consequences there’ll be no post for probably another week…





Time for lunch

9 11 2010

Ha, it’s been a while since I’ve managed to come up with a pun-like title. But let’s step aside from what is probably my own askew sense of humor and into the realms of C#. Yes that’s right, I’ve left the barren wasteland that is ActionScript 3.0 in favour of greener pastures, namely C# [read as C-Sharp but don’t ask me why, I guess C++Java sounded weird].

DISCLAIMER: In no way am I suggesting that C# is anything other than its own language. Though clearly inspirsed by C++ and Java at first. It has now evolved into something which is different and stands, quite proudly, on its own.

Right, what am I doing?
Several things and all at once. My main tasks for the past week and a half have brushed me against the GDI+, Windows Forms and XML. The entire project was a supposedly simple implementation of an animation/drawing type application. I say supposedly since I’ve never touched GDI+, barely glimpsed Forms for College [and possibly the worst teacher in the world, but more on that on a different post] and well, I’ve been mucking around XML with ActionScript so I felt fairly comfortable there. Also, there is no such thing as a useful program that is also simple…

Let me get this out of the way now, if there is one thing ActionScript 3.0 got right it’s the XML support; easy and fun. C#, not so much, I’ve ended up using the XmlDocument object which represented my entire file and just iterated over the nodes I wanted, plus created a couple of useful static functions for extracting things like Size and PointF. On that note I would also like to say that creating a coherent data model and a unified application-based interface for extracting said data is a practice I heartily recommand as it will save time down the line.

What about the other two though? Well, Forms and the GDI+ API weren’t terribly hard to come to grips with to be honest, C# being a fairly intuitive sort of language and Visual Studio 2010 being a fairly [read, very very very] intuitive IDE [when it doesn’t crash :P]. I did come across several issues however.

The first of which is the flicker effect. That is, invalidating the Form forces a redraw of the “screen” but with only one buffer the whole process flickers worse than a drunken firefly. Solution -> double buffering. How?

Normally I would simply have my rendering loop running at full steam and flipping buffers like there’s no tomorrow, normally. The problem here is that a Form is an event based system, forever loops [unless stuck in a different thread] are a big no-no. There are a few ways out there of doing it and I’m sure mine is far from optimal, but it works and is simple to implement. Here’s how I solved it:

Create BackBuffer;
Create RenderTimer;
Every time the RenderTimer ticks, update the BackBuffer, flip and clear.

I’ll talk about the RenderTimer right after but for now all you need to know is that, like everything else, the Windows.Forms.Timer is an event based object which generates a Tick event every X interval [programmer provides the X] and I’ve just used the Toolbox to attach it to the main form. The rest of the code looks something like this:

//Data you'll need, stick it somewhere private.
  private Graphics      _frontBuffer = null;
  private Bitmap        _imageBuffer = null;
  private Graphics      _backBuffer  = null;
private void InitializeDoubleBuffer()
{
  _frontBuffer = this.CreateGraphics();
  _imageBuffer = new Bitmap(this.ClientSize.Width, this.ClientSize.Height, _frontBuffer);
  _backBuffer = Graphics.FromImage(_imageBuffer);
}

Provide a simple interface for something which can be drawn [derive and override as required]:

interface IDraw
{
  void Draw(Graphics surface);
}

and finally in the tick event:

shape.Draw(_backBuffer);
_frontBuffer.DrawImageUnscaled(_imageBuffer, 0, 0);
_backBuffer.Clear(Color.Black);

And voila! flicker-free rendering.

I was going to talk about the timer system and the problems I’ve had with synchronizing the animations but I’ve ran out of time, there’s work tomorrow and, yup you guessed it… Still need to do the dishes 😀
Good Night!

“the black flame of evil is burning and growing, Queen… queen of the dark horizons! “





Same Bat time

1 11 2010

Full time work, less time blog… Updates will resume a weekly schedule around Friday.