Never hide a TUF in a TUC

This slogan (never hide a TUF in a TUC) was introduced (to me at least) in 2010 by Michael Feathers. Turns out it is a pretty good tool to explain and steer people in the right direction when they are new to writing unit tests. But what is TUF and TUC?

Test Unfriendly Features (TUF)

TUFs are things that are either slow and/or tightly coupled to something that is hard to fake in a test. For example: file/network/storage access, long computations, 3rd party frameworks/libraries and global/static variable manipulation.

Especially the fact that any 3rd party interaction is considered a TUF is important to remember I think. I've seen people having a tendency to forget that.

Test Unfriendly Constructs (TUC)

TUCs are things in the language you use that are hard to fake. This does not mean you should void these constructs or that they are bad. Just that they don't mix well with TUFs. Examples are: Any constructor, anything static, const/read-only things, non-virtual or sealed things and private methods.

Especially hiding TUFs behind something non-virtual is one of the most common mistakes I make myself.

Why is this useful?

Testable code is in it self not the goal I think. But loosely coupled code is a desire. By following the simple rule of never hiding a TUF in a TUC some of the most common mistakes you can do in your code will be avoided. And that is regardless of if you are actually going to write tests for your code or not. I find that pretty nifty.

Just remember that both TUFs and TUCs are fine to use. Just don't use them together!

No comments:

Post a Comment