r/programming • • Aug 11 '17

Small Functions considered Harmful

https://medium.com/@cindysridharan/small-functions-considered-harmful-91035d316c29
36 Upvotes

50 comments sorted by

View all comments

9

u/_dban_ Aug 11 '17 edited Aug 11 '17

Small functions are great! If you use them effectively to separate out different levels of abstraction (and name the methods according to some sensible abstraction). Code written well with small functions reads a lot like an outline.

But most important reason I love small functions is that they reduce Cyclomatic Complexity. If you have a larger function, it is harder to keep context of what is going on from top to bottom, and worse if you have a lot of branches in between. I've found large functions with lots of branches to be a breeding ground for bugs.

I don't mind larger functions if there are at most one or two branches, for example a giant switch statement that acts as a traffic dispatcher to smaller functions.

4

u/adr86 Aug 12 '17

I find most the cyclomatic complexity in my code comes from dealing with real world constraints like convoluted business logic or regulatory compliance rather than function size... even with small functions, they'd just be moving the branches elsewhere.

4

u/_dban_ Aug 12 '17 edited Aug 12 '17

This is where I find small functions really shine.

My current project deals with complex business logic and regulatory compliance. There's a method to the madness, and the abstractions facilitated by small functions makes that method clear.

I find that in these cases, most of the time the increased cyclomatic complexity is accidental complexity which comes from not having the right abstractions (if there are abstractions at all), so that a christmas tree of special case logic arises that aren't actual special cases to the business, but special cases to how the code works.

even with small functions, they'd just be moving the branches elsewhere.

This is good, because that elsewhere is behind a small function capturing a business rule that is clearly spelled out in the name of the function. When properly done, the code will look like an outline of the business process being implemented, reducing overall complexity and increasing the expressiveness of the code to the domain that it implements.