<< Great Ideas: Popularize? Trivialize? | Home | It's Really Quiet Here >>

Test-First This!

Cedric Beust posted a few tricky interview questions in FUN WITH BITS

There are three categories of bit-shifting questions that I usually pick from, in increasing order of difficulty:

  1. How can you determine if a number is a power of two?
  2. How can you clear the rightmost bit?
  3. How can you count the number of 1 bits?

Answers were given in the blog. However they were derived at logically. In this day and age of the test-first hype, I would like to challenge its adherents to solve the problems in a test-first fashion.

Any takers?



Re: Test-First This!

Like this?
  assertTrue(isPowerOfTwo(1));
  assertTrue(isPowerOfTwo(2));
  assertTrue(isPowerOfTwo(4));
  assertTrue(isPowerOfTwo(7));
  assertFalse(isPowerOfTwo(3));
  assertFalse(isPowerOfTwo(5));
  assertFalse(isPowerOfTwo(6));
and so forth... BTW, Cedric' answer for the power of two question is wrong (or at least insufficent). Try it with -254, for bytes. With a TDD approach, you'd know that either you hadn't considered negatives (none in the tests) or had done so (test cases for them).

Re: Test-First This!

While I personally don't test as much as I probably should, test first doesn't mean that you don't think logically, it simply means that you write the test first. So, for example, for the first of Cedric's problems (or is it the second? The one that makes numbers even numbers ;) - you would build a test something like assert myEvanifier(5) == 4; assert myEvanifier(2) == 2; assert myEvanifier(13) == 12; assert myEvanifier(Integer.MAX_VALUE) == (Integer.MAX_VALUE-1) Then you would write a version of the code however you chose. Then if you wanted to optimise your implementation later, then you could do it with the tests protecting you. The only reason that you write the test first is so that you don't accidently craft the test based upon the code you've just written. I guess.

Re: Test-First This!

We can talk all day long about why it is possible to solve the puzzles using a test-first approach in the abstract.

What I'm looking for is a concrete example of a solution using test-first.

My guess is that none of the solutions can be arrived at using a purely test-first approach.


Add a comment Send a TrackBack