Writing Code for the Next Person
Function Length
Perhaps one of the best code style recommendations I received in my career was to never write a function that was longer than 100 lines long. The argument was that, if you need more than 100 lines, then you can probably find a way to restructure that function into a few, smaller functions that are easier to read, easier to maintain, and less likely to contain bugs. Unit testing is also simplified and more narrowly scoped.
There are a few exceptions to this rule:
- If the code is modestly over the limit, fine. Don't break a short function only for the goal of keeping it within 100 lines.
- If breaking the code into pieces actually reduces readability, then allow it to be longer. This is generally true in functions that perform a simple task, but just contain a number of non-breakable steps.
- If breaking the code apart has a serious, negative impact on performance, then leave it as a unit.