Code Quality Essentials

Code quality an essential factor for the long-term success of a software system. At the same time, code quality is in most cases opinion-based and up for discussion. Actually testing for bad code is like testing for obscenity: you know it if you see it. After reading Clean Code I realised that this topic is and always will stay subjective. In the end, Clean Code is basically the (expert) opinion of Uncle Bob Martin from 2008.

Recently people (see e.g. here and here) start rightfully questioning the advice in the book. I could start ranting about Clean Code, too, but this would be too easy. A rant without alternative is just hot air: criticism without being constructive, you cannot learn anything from it.

What are the guidelines we really need? I’ll attempt to build my personal, highly subjective collection, with references to the sources.

»When to test?

Difficult question. I found some random notes on » The Internet «, Is TDD Dead? and the corresponding HN thread.

My view coincides with Andrew Dalke’s Problems with TDD:

Just use common sense and » good unit testing «, without the extra bells and whistles of TDD.

When to write tests?

  • Unit tests should test the API of a cohesive piece of software, something with a clear boundary (aka the unit).
  • Use tests to hunt down edge cases
  • Adding a new class is not the trigger for a test, but the trigger is implementing a requirement (source)

One test per (desired) external behavior of the unit, plus one test for every bug.

»One level of abstraction

You should not mix different levels of abstraction in one function. Either the function performs low-level or high-level tasks, but not both. Good to see if you zoom out and look at the syntax colour distribution (cq, nocq).

»No side effects

Functions should not have side effects (cq, nocq)

  • functions should do approximately one thing (definitionssache)
  • that output arguments are to be avoided in favour of return values.
  • He says that functions should generally either be commands, which do something, or queries, which answer something, but not both.
  • Funktion max. ein Schirm lang (80 Zeilen)
  • Keep dependencies small
  • removability as measurement of code quality?!

Regeln

  • don’t fight stupid and make more awesome
  • not on biggest problems, but biggest opportunities
»Function length

Functions should fit on a screen, which translates to about 80 lines. I guess my personal I cannot ignore this anymore point would be 100 lines.

»Consistent naming

Function names should be descriptive, consistent and verb phrases. Choose them carefully (cq, nocq).