There is an axiom of good software craftsmanship that goes like this:
A function should do one thing and do it well.
Never heard that before? Yep. It's a thing – an industry-accepted principle for crafting good software. But why? Why is this a thing?
Well, functions that do one thing are small. How small? Oh, say, 20 lines or less. Yes, and smaller. But imagine the benefits of a small function.
But wait, you say some functions must do more than one thing.
Well, sure.
But they do this by invoking other functions that do one thing. So higher-level functions should read like a checklist as they invoke other functions to do the work for them. Like this:
Some functions just organize the work. They give us a logical flow without the details. If you want details, then you have the option of drilling down into lower-level functions. When traversing a giant function with multiple snow geese formations, you don't have that option.
There's a corollary to the one-thing principle.
If a function does one thing well,
its name should say, well, what it does.
Small functions are only as helpful as the names we give them. We should know what a function does simply by reading its name. We spend about 75% of our time understanding code, 20% of our time changing it, and only 5% writing it (source). Well-named functions save everyone time and mental cycles.
Functions do something or answer a question. Do-something functions use an action verb to describe what they're doing.
Functions that answer a question always return a boolean. We name them as a question for clarity.
True. For now, at least. There are other important principles that we can explore later. But crafting good functions is fundamental to crafting good code.
A function should do one thing and do it well.
If a function does one thing well,
its name should say, well, what it does.
Rob Witty
Boston
Software developer crafting solutions for over 40 years on various platforms, databases, and languages. IT is about mastering one new technology after another. Hiker, traveler, admiring the wonder in things great and small.