DEV Community

Discussion on: Solve this simple problem with TDD

Collapse
 
rossdrew profile image
Ross

The process that I follow.
1- Write a set of tests (input--->expected-output)
2- Pick the simplest test case to solve. (RED)(Write a failing spec)
3- Write the most naive code change that solves the current set of tests. (GREEN)
4- Check if DRY is needed (Refactor)
5- Go back to 2

Firstly, TDD is not writing a set of tests. It's writing a test that fails then writing functionality.

So (like I said earlier), you write a RED test:

Input: []
Expected Output: []

You then write the simplest code to solve this problem and GREEN the test above

fun flatten(input)
   return input

Then your next test case

Input: [1]
Expected Output: [1]

and it passes, so next

Input: [1,2]
Expected Output: [1,2]

Next

Input: [[1,2]] -> [1,2]
Expected Output: [1,2]

This one does RED. So we write the code to GREEN it

//May be wrong - just throwing pseudocode out there
fun flatten(input)
  output = []
  for (int i=0; i<input.length; i++)
    if input[i] is array
      output.addAll(input[i])
    else
      output.add(input[i])

[1,[2,3]] -> [1,2,3]
[[1,2],[3,4]] -> [1,2,3,4]

Both start off green

[[1,2,[3,4,5]],6,7] -> [1,2,3,4,5,6,7]

RED, so expand implementation

//May be wrong - just throwing pseudocode out there
fun flatten(input)
  output = []
  for (int i=0; i<input.length; i++)
    if input[i] is array
      output.addAll(flatten(input[i]))
    else
      output.add(input[i])

GREEN.

[[1,2,3,[4,5,6]], [7,8,[8,10,11]]] -> [1,2,3,4,5,6,7,8,9,10,11]

Starts off green.

At some point there is no naive change to solve the tests and I need to rewrite the whole solution.

There's not always a naive change but in this case I'm not sure where the non naive code change happens. You need to add a loop pretty early but that's the easy way forward.

Collapse
 
delbetu profile image
M Bellucci

You raise a good point when saying that starting with a list of tests is not TDD.
To clarify those tests are not run all together from the beginning.
When I start coding all of them are commented out and during the TDD cycle I just decide which of them uncomment.
Starting with a list of tests is done by J.B.Rainsberger
on his course introduction to TDD

In the other hand maybe restricting to an initial list of test is not a good way to lead to a solution.
I tried writing the test that makes more sense for the current tdd-cycle and then I reached a solution (updated this in the description).

your solution seems to be a valid one I didn't try it.
Thanks for taking the time to read and solve this problem.