Red Green Repeat Adventures of a Spec Driven Junkie

TDD Practice - Divide without Divide

From this post there is a way to implement divide without /, make tests pass, and have a great runtime.

(The first post in this series is here)

A key to Test Driven Development is:

Write one and only one test and the simplest code to pass the test.

Write One Test Only

In test driven development, “tests first” does not mean write all your tests first. “Tests first” refer to having one test first, then code.

When coding, it is easy to worry about all the situations, edge cases you will have, which is great, so write them down.

Solve your immediate problem, then get to the next problem.

Use Simple Code

When making a test pass, just focus on the simplest code for the test.

The best, high performance, debuggable, and readable code for any situation is:

No Code

This blew my mind the first time I heard it. 🤯

The next best is to have as simple code as you need.

If the test is:

it 'divides by 1' do
  divide(1,1).to eq(1)
end

The simplest solution would be:

def divide(a,b)
   return 1
end

This solution is simple, performant, debuggable, and readable. The test is only testing for the one case. This also satisfies the higher level requirement of “implemen divide without /”.

What about Solving the Problem??

Honestly, the above implementation does satisfy the conditions. To solve the problem better, one would just write more tests in this fashion:

  • Another test
  • Code
  • Repeat

At every single step, maintain simplicity.

Of course, at some point, you get bored and can jump forward to this test:

it 'divides 100 down to 1 by 1 to 10' do
  for 100..1 do |a|
    for 1..10 do |b|
      divide(a,b).to eq(a/b)
    end
  end
end

Note: this test maintains the requirement of not using / - using / is fine in tests. ;-)