Graduate Program KB

Clean Code

Chapter 9

Three Laws of TDD

  • Laws:

    • First Law: You may not write production code until you have written a failing unit test
    • Second Law: You may not write more of a unit test than is sufficient to fail, and not compiling is failing
    • Third Law: You may not write more production code than is sufficient to pass the currently failing test
  • Essentially, tests and production code are written together

Keeping Tests Clean

  • Tests should be well designed, partitioned, descriptive and contain good variable names

  • Not following these rules create problems as production code evolves, making tests hard to change

    • The more coupled test code is, the more time you'll spend writing tests than production code
    • Old tests start to fail as production code is modified
    • Tests become a liability at this point
  • The fear of breaking code goes away with high test coverage

    • Tests enable change
    • Adding small incremental changes reduces bugs
  • Ensure readability, focus on clarity, simplicity and density of an expression

  • Build-operate-check pattern

    • Build up test data
    • Operate on the test data
    • Check that the operation yielded the expected results

Tests

  • Minimise assertions in each test case, generally a good guideline is once per test case

  • Split duplicate code in test cases using template method

    • Put given/when parts in the base class
    • Put then parts in different derivatives
  • Test one concept in each test case, single responsibility principle

  • Clean tests follow F.I.R.S.T. rules

    • Fast: Tests should run fast and frequently
    • Independent: Tests should not depend on each other
    • Repeatable: Tests should be repeatable in any environment
    • Self-Validating: Tests should have a boolean output, either they pass or fail
    • Timely: Tests need to be written in a timely fashion