A Test-Driven Implementation of Huffman Data Compression — Part 9 (final)

In Parts 18 of this series, I’ve shown how to build a Huffman compressor and decompressor.

I followed a strict test-driven approach: write a test, run the test and verify it fails, write the code, re-run the test and verify it passes, refactor the code if needed. Repeat.

Adopting TDD has a few benefits:

  • you focus on what the code is supposed to do, not how to do it;
  • you can stick to simple implementations and refactor them safely later;
  • you get a whole suite of tests emerging at the same time as your code;
  • your code naturally comes along as a set of loosely-coupled components;
  • testing-first is more fun (at least for me);

A few final thoughts in random order:

London or Chicago?

  • sketch your class: write a skeleton that represents its behaviour;
  • write a test to exercise that behaviour;
  • write the code;
  • refactor the code if needed.

SOLID TDD all the way down

In my opinion, adding new functionalities to a class should always be done in a TDD way, as well as fixing any bugs.

Is TDD really the best way to write code?

TDD works very well when pair-programming, and especially when mob-programming: people collaborating on a problem are unlikely to jump straight into coding; first, they must collectively understand the criteria of satisfaction of the problem to solve.

TDD helps a lot in that sense.

The idea is that acceptance criteria drive tests and tests drive development.

Does TDD takes a long time?

A class to represent a bit, really?

Of course I did it for “didactical” (so to say) purposes, but this is the problem with object-oriented languages like Java: everything is a class. You are forced to follow a single paradigm, which is not ideal.

Also, the proliferation of so many immutable objects in memory might not be ideal in terms of footprint and performance.

Further optimisation

That is just a change to the internal logic of that class and the test is already there to make sure the behaviour of the class doesn’t break. However, should you write any collaborators for that class for that specific purpose, they should be developed in a TDD way too.

The power is in the algorithm, not the tests

End of my rambling. That’s all! Happy TDD-ing! :)

You find the code for the 8 parts of my series here:

https://github.com/andrealaforgia/tdd-huffman-compression

Software Engineer at Oracle