Let’s play tennis, with TDD

TDD & Code Kata’s

Now I’m working since more than four months as a software engineer at bbv Software Services in Switzerland. Every new employee at bbv needs to attend several courses (bbv Academy) to improve and extend his skills towards a good software developer. After my Scrum Master course, the next one on my schedule was Test Driven Development.

In addition to the theory why TDD, clean code and pair programming is highly desirable the course was accompanied with hands-on code kata’s. For those who don’t know what a code kata is, here is a citation from Wikipedia:

A code kata is an exercise in programming which helps a programmer hone their skills through practice and repetition.

One kata of the course was the Tennis Scorer. The goal was to implement a mechanism, which prints the score of a single game (therefore there are no sets).

Our Referee

The rules given were the following:

  1. A game is won by the first player to have won at least four points in total and at least two points more than the opponent.
  2. The running score of each game is described in a manner peculiar to tennis: scores from zero to three points are described as “love”, “fifteen”, “thirty”, and “forty” respectively.
  3. If at least three points have been scored by each player, and the scores are equal, the score is “deuce”.
  4. If at least three points have been scored by each side and a player has one more point than his opponent, the score of the game is “advantage” for the player in the lead.

Our implementation should be based on the ITennisScorer interface, which of yourse was changed during the exercise.

<pre>namespace Tennis
    public interface ITennisScorer
        void AchievesScore(Player player);

        string GameScore { get; }

    public enum Player

Because it was a TDD course, we needed to build up a TODO list of appropriate unit tests first (e.g. Game just started, no one scored so far, expected score “love”).

Then we implented the unit tests one by one. Each of them had to fail first. Then came the actual implementation, test should pass afterwards. Code Refactoring -> All tests should pass.

Our Players

My initial implementation was blotched with many if statements, handling all the special cases for the game score (deuce, advantage, …). I also had code duplication, because I needed to track and update the score of player A and B separately.

But here comes the ultimate advantage of TDD. You’re not afraid anymore to refactor your code to a better architecture and solution. Because you know you can (and should) always run your unit tests and see if everything is still behaving as desired. You can sleep comfortably without to fear the next morning from an upcoming design change. Ok, I know. Some can still sleep during the nights without TDD, but they will be haunted by bad dreams 😉

So I refactored my code and eliminated the code duplication. Instead of using an enum to track the actual player score, I simply use a two-dimensional array, which holds all the possible scores of a game.

namespace Tennis
    public class TennisScorer : ITennisScorer
        private int scoreA;
        private int scoreB;

        private const string GameA = "gameA";
        private const string GameB = "gameB";
        private const string AdvantageA = "advantageA";
        private const string AdvantageB = "advantageB";

        private static readonly string[][] PlayerScores = new[]
                new[] {"love",  "15:0",     "30:0",     "40:0",     GameA},
                new[] {"0:15",  "15:15",    "30:15",    "40:15",    GameA},
                new[] {"0:30",  "15:30",    "30:30",    "40:30",    GameA},
                new[] {"0:40",  "15:40",    "30:40",    "deuce",    AdvantageA},
                new[] { GameB,   GameB,     GameB,      AdvantageB}

        public void AchievesScore(Player player)
            switch (player)
                case Player.PlayerA:
                    UpdateGameScore(ref scoreA, ref scoreB);
                case Player.PlayerB:
                    UpdateGameScore(ref scoreB, ref scoreA);

        public string GameScore
            get { return PlayerScores[scoreB][scoreA]; }

        private void UpdateGameScore(ref int playerToAddScore, ref int opponentScore)
            if (GameScore == AdvantageA || GameScore == AdvantageB)
            else if (GameScore != GameA && GameScore != GameB)

The Regulating Authority

I also refactored my unit tests. There were many tests, testing all the possible game processes. But my course instructor gave me the hint to use Nunit’s RowTest. Instead of writing many, almost identical tests for each case, I wrote just one parametrized unit test and the many case were provided as a parameter.

namespace Tennis.Test
    using NUnit.Framework;
    using FluentAssertions;

    public class TennisScorerTest
        private TennisScorer testee;

        public void SetUp()
            testee = new TennisScorer();

        [TestCase("", "love")]
        [TestCase("A", "15:0")]
        [TestCase("AAB", "30:15")]
        [TestCase("AAAB", "40:15")]
        [TestCase("BBB", "0:40")]
        [TestCase("BBB", "0:40")]
        [TestCase("ABABAB", "deuce")]
        [TestCase("AAABBB", "deuce")]
        [TestCase("AABBAB", "deuce")]
        [TestCase("AAABBBA", "advantageA")]
        [TestCase("AAABBBB", "advantageB")]
        [TestCase("AAAA", "gameA")]
        [TestCase("AAAAA", "gameA")]
        [TestCase("AAAABBBBBB", "gameA")]
        [TestCase("AAABBBBB", "gameB")]
        [TestCase("ABABABABABABABABABABABAA", "gameA")]
        public void PlayerScores(string game, string expectedScores)
            foreach (var currentScore in game)
                switch (currentScore)
                    case 'A':
                    case 'B':

References & Coaches

If you want to practice your programming skills, I can encourage you to do some code kata’s, or similar challenges, to stay fresh in your head.

Here is a list of some useful sites with some brain-teasers and, if given, their solutions:

My Tennis Scorer implementation is available on GitHub.

2013-03-10 | Posted in: C#, Coding | Comments Closed

High delay in RS232 communication on a PXA270

I’m experiencing a long delay (1.5ms – 9.5ms) in a RS232 communication on a PXA270 RISC PC/104. I want to minimize the long delay but I’m a beginner with embedded devices and C++ so I think I’m missing something.

RS232 delay on PXA270

RS232 delay on PXA270

The mentioned delay is at the time when the PXA board receives a packet from the external device via RS232 (115200 baud) until it sends an ACK custom packet back to the external device. I measured the delay on the PXA board with an oscilloscope, one channel at the Tx (green) and the other on the Rx (blue).

The PXA board is running an Arcom Embedded Linux (AEL). I know, it’s not a real-time OS, but I still think, that an average delay of 4.5ms is way too high for extracting the received packet, verify it’s CRC16, construct an ACK packet (with CRC) and send it back the serial line. I also deliberately put the CPU under heavy load (some parallel gzip operations) but the delay time didn’t increase at all. The maximum size of a received packet is 30 bytes.

A C++ application (another former co-worker wrote it) is handling the reception of the packets and their acknowledgement. One thread is sending and the other is receiving the packets.

I thought that the RTC on the PXA board has a very bad resolution and the AEL can not align the timing to the internal RTC resolution. But the RTC has a frequency of 32.768 kHz. The resolution is sufficient, still don’t explain the high delay. Btw, I think the OS is using the internal PXA clock (which has also a sufficient resolution) instead of the RTC for the timing.

Therefore the problem must be in the C++ app or in a driver/OS setting of the RS232 interface.

The following control flags are used for the RS232 communication in the C++ application according to the Serial Programming Guide for POSIX Operating Systems:

// Open RS232 on COM1
mPhysicalComPort = open(aPort, O_RDWR | O_NOCTTY | O_NDELAY);
// Force read call to block if no data available
int f = fcntl(mPhysicalComPort, F_GETFL, 0);
f &amp;= ~O_NONBLOCK;
fcntl(mPhysicalComPort, F_SETFL, f);
// Get the current options for the port and set the desired values
tcgetattr(mPhysicalComPort, &amp;options);
cfsetispeed(&amp;options, baudRate);
cfsetospeed(&amp;options, baudRate);
// no parity (8N1)
options.c_cflag &amp;= ~PARENB;
options.c_cflag &amp;= ~CSTOPB;
options.c_cflag &amp;= ~CSIZE;
options.c_cflag |= CS8;
// disable hardware flow control
options.c_cflag &amp;= ~CRTSCTS;
// raw input
options.c_lflag = 0;
// disable software flow control
options.c_iflag = 0;
// raw output
options.c_oflag = 0;
// Set byte times
options.c_cc[VMIN] = 1;
options.c_cc[VTIME] = 0;
// Set the new options for the port
tcsetattr(mPhysicalComPort, TCSAFLUSH, &amp;options);
// Flush to put settings to work
tcflush(mPhysicalComPort, TCIOFLUSH);

I think I’m missing something very simple. I think, that if the process of the app is running under a higher priority, this will not solve the problem. There must be something, which instructs the RS232 driver to handle the requests with a higher priority to minimize the latency.

Does anyone have any ideas? Thank you very much in advance for your help.

The Solution

I was able to reduce the delay to ~0.4ms. The command setserial(8) was referenced in the AEL manual. And bingo, I found the low_latency flag there with the following description:

Minimize the receive latency of the serial device at the cost of greater CPU utilization. (Normally there is an average of 5-10ms latency before characters are handed off to the line discpline to minimize overhead.) This is off by default, but certain real-time applications may find this useful.

I then executed setserial /dev/ttyS1 low_latency and the delay was reduced to ~0.4ms *yay*
But I wanted to implement this behaviour in the C++ app, without setting this flag globally with setserial (this command is by default not included in all distros).

I’ve added the following code lines, which had the same effect as the low_latency flag from setserial:

#include &lt;sys/ioctl.h&gt;
#include &lt;linux/serial.h&gt;
// Open RS232 on COM1
mPhysicalComPort = open(aPort, O_RDWR | O_NOCTTY | O_NDELAY);
struct serial_struct serial;
ioctl(mPhysicalComPort, TIOCGSERIAL, &amp;serial);
serial.flags |= ASYNC_LOW_LATENCY; // (0x2000)
ioctl(mPhysicalComPort, TIOCSSERIAL, &amp;serial);

Have phun 🙂

2011-01-12 | Posted in: C# | Comments Closed

1km Notenstatistik

Jedes Semester werden die Noten anonymisiert von der HSLU T&A veröffentlicht. Einige Stunden später erscheint auf der 1km Seite auch die entsprechende Notenstatistik.
In der Statistik ist die prozentuale Verteilung der Noten für die Module ersichtlich. Zudem kann jeder Student seine Noten über die persönliche Matrikelnummer abfragen.
Die veröffentlichten Noten wurden bisher in einem aufwendigen Verfahren manuell konvertiert um sie in die Datenbank der Webseite abzufüllen. MS Word & Excel sowie Regex Befehle im Texteditor waren für die Konvertierung notwendig. Der Aufwand belief sich für jedes Semester zwischen 1-3 Stunden.

Nun habe ich ein kleines C# Programm geschrieben, welches die Noten aus der veröffentlichten PDF Datei einliest, diese konvertiert und anschliessend in einem geeigneten Format für das PHP Skript der Webseite abspeichert.

Folgende Features weist das Programm auf:

  • Modularer Code (Strategy und Factory Pattern)
  • Die einzelnen Tasks sind zur Laufzeit austauschbar
  • Tasks werden in Threads abgearbeitet
  • Nutzung von eigenen Events und Eventargumenten um über den Fortschritt der Tasks zu benachrichtigen
  • itextsharp Bibliothek um PDF Datei einzulesen
  • Speicherung der Applikationseinstellungen in Properties
  • Nutzung von ILMerge um alle Abhängigkeiten in eine EXE Datei zu packen

Das C# Projekt gibt es hier.

Notenparser in C#

Notenparser in C#

2009-01-10 | Posted in: C# | Comments Closed