How small should functions be

code formattingfunctions

I'm new at writing professional code (the bulk of my experience is with personal projects) so excuse me if this is trivial. When I write code I find myself being a little inconsistent with how much functionality I include in one function. If I know it's code I'm going to reuse later I'll make a separate function, but when it's something like a check I often find myself either writing a one line function or writing the one line check in every function that needs it.

How little functionality is too little? Is return foo == null; too small and could be included in a bigger function as an if statement, or is it acceptable to write a separate function for just a null check?

Best Answer

Make them as small as possible, but no smaller. The limiting factor here has nothing to do with the work being done. It has to do with if you can think of a good name. A decent vocabulary is a powerful thing.

Give me a choice between a flat 100 line monstrosity and a 10 line function full of functions named procedureA(), procedureB(), and I'll take the monstrosity without even looking.

Give me good names, that abstract a single idea, that don't surprise me when I look inside, and I'll happily choose the little functions.

If you can't think of a good name then please don't create a secret language that only the painfully initiated can speak. I've been hazed enough for one lifetime.

Related Topic