Naming Functions & Keeping Them Simple
Every time I write a function or method, I take a moment to describe it to myself in plain English. Doing so serves two purposes: It helps me determine if the function is too complex, and it helps me come up with a good name for the function.
If the description I come up with for a function is more than a single sentence, or if that single sentence contains the word “and”, that indicates the function is too complex. In order to keep code understandable and maintainable, each function should serve a single purpose. There are, of course, exceptions to this rule, but they’re few and far between.
If a function does more than one thing it’s likely I’ll end up needing to do those individual things separately at some point in the future, so it’s a good idea to stop and break the function up into individual pieces now before things get too out of hand. It’s also much easier to understand and maintain code that’s broken up into small, easy-to-digest chunks with few (if any) dependencies on each other.
Once I have a function that produces a proper single-sentence, single-purpose description it’s usually easy to turn that sentence into a good, descriptive name for the function. Reduced code complexity and great function and method names with one simple technique!
So, how would you describe your functions?