Better cycle time with Unit tests

What is cycle time: It is time needed to complete a function/task from start to finish.

If some one tells you "you can complete the feature faster by writing unit tests" what will be your reaction. Probably you won't agree to it. It is counter intuitive for someone not initiated into TDD. How come writing more code, reduces total time for development?

Let me start with the cycle of TDD.

  1. Write a test first. It will/should fail since there is no code which will make it work.
  2. Write code to make the test pass. 
  3. Refactor to make the code readable.















Repeat the process till you complete the feature. 

If you have observed a brick layer laying bricks. He will put little cement. Then he will lay the brick. Then he will adjust the brick to make sure it is laid right. This process is repeated till the wall is complete. 

If you take the parallel to software development then you should make sure each line performs as it is intended in the overall feature. As a brick layer will not put a line of bricks before adjusting them all. Same goes for the software. Why do you want to wait for the feature to complete to write tests or even test it out manually?

Best approach is to check feedback as much as possible. Write a small test and code for that test. This ensures feedback for the code you are writing. Now you do not have to wait till everything being written to test your code. Since this feedback helps you to keep testing your code as you write it, you achieve a faster cycle time. When you wait till the end to test your code you need to keep many threads running in your head. You need to keep the state of different variables you are using. You need lot more mental power to keep focused. This takes a toll and you will write code slower and slower. Any small distraction and you need to pick up from a point.

Same time when you have the tests written before hand you have put lot of sign boards and it is lot easier to follow. You do not need many threads to be running in your mind. Tracking those threads are coded now. This entangles the complexity of the piece you are writing. Now you are putting together small blocks of lego to build that master piece. 

There are some gifted programmers who can focus and write many lines of code at a stretch and it will work as intended. But these veterans will follow TDD as it brings out better code. For the mere mortal programmers TDD is the way to go if you want better code. Better code will result in better product. 

From my experience it takes 30% less effort to write same feature when you follow TDD.

Comments

Popular posts from this blog

ChatGPT for cavemen

Greedy computing with API

Event driven architecture for micro services