Scientific Method as a case for TDD

Posted on by Chris Moore

In an earlier post, I wrote about how I had the realization that I am not a Computer Scientist.

Which got me thinking about scientists…

And within the confines of my own twisted little mind this idea began to form: Is the Scientific Method itself a case for TDD? Some quick googling proved I’m not the first person to draw these parallels…

Let’s get in the-way-back-machine and go to elementary science class. Let’s go back to the first time you learned about the Scientific Method.

The Scientific Method is defined as:

  1. Ask a Question
  2. State a Hypothesis
  3. Conduct the Experiment
  4. Analyze the Results
  5. Make a Conclusion

And at it’s core, TDD is defined as:

  1. Add a Test
  2. Watch Test fail
  3. Write Code
  4. Run Tests
  5. Refactor

C’mon, they even have the same number of steps! :)

Let’s look at the steps individually using the idea of a basic User update form submission…

###Ask a Question / Add a Test

“When I submit this form, will the User get updated?”

vs

###State a Hypothesis / Watch Test fail

“Yes, the User should update when the form submits”

vs

###Conduct the Experiment / Write Code

The Experiment IS the Code…

###Analyze the Results / Run Tests

“Was my Hypothesis correct? Was the User updated?”

vs

Those beautiful green dots for a passing test or the nasty red F’s

###Make a Conclusion / Refactor

“Yes, the User successfully updated” or “No, the User failed to update”

vs

“Cool. Tests pass. Let’s pretty it up a bit if we can!” or “Booo. Tests fail. Let’s fix it, then run the Test again!”

Many times, I’ve heard the argument against TDD that “sometimes you’re not really sure what to test until after you’ve written it”. To me, that sounds like a problem with Ask a Question / Add a Test. The question is too broad, or not defined well enough.

“Will super complex operation X give me output Y? Oh god! It’s a 200 line method!”

Remember, Big Things are made up of Small Things!

“Will portion X of super complex operation Y give me output Z?”

If “super complex operation Y” doesn’t really have a “portion X”, I’d think that’s a code smell! Maybe there’s some refactoring to be done there to turn “super complex operation Y” into more manageable, testable portions! Those guys at the LHC don’t just fire that thing up and say “Hey! Let’s throw Jeff Goldblum and a fly in there and we’ll just work backwards from there!”. They first make sure to have a Defined Test to solve first!

And there you have it, using the Scientific Method as a case for TDD! Any questions? Leave a comment for us! We’d like to hear what you think!

 
comments powered by Disqus