Thursday, February 23, 2012

Principles for writing testable code

In order to write code that are easy to test then there are a few principles that must be followed:

  • Dependencies must be injected, use property- or constructor injection or an injected service locator.
  • Avoid static variables.
  • Avoid calling static methods unless they are only doing in-memory operations.
  • Mark public methods as virtual or use interfaces.
  • Classes and methods should be small. Preferably not longer than one screen size. Use the single responsibility principle to achieve this - a class should only be responsible for doing one thing = one public method (except from method overloads and facade classes).