Photo by: Gaby Av
What are the ideal properties of a function and when should you refactor a functions? Or from another angle, when is the best time to refactor a function out, restructure within or just leave it? In the last week or so I’ve noticed an interesting pattern in functions written by some slightly novice developers. I got to thinking about how to best give constructive feedback. But something I found interesting about all of is that the structure of the functions, at least on the surface, seemed to meet all the traditional best practices of a function. They performed a single purpose, were created to avoid repetition, etc. But the code was awkward to work with and functions almost obfuscated rather than simplified. So what attributes made them difficult to work with and kinda smell of code rot? So I thought I would list out some further considerations when breaking a functions out.
What the heck is functional mutation? Well I did just make the word up but it seemed appropriate. Usually, this is a sneaky violation of “functions should perform a single purpose”. It happens when a function’s output varies unpredictable from what can been gathered from the function’s name and its inputs. This is usually caused when the code inside the functions varies output wildly due to non-intuitive conditions, at least as seen by the outside observer. It really pays to leave conditional logic which impacts the straightforwardness of a function in a higher level of code. If that just doesn’t seem reasonable then usually that’s an indication that it’s to rethink the structure to match the conditional lines.
When a function can not perform its required task due to its dependence on another function it’s usually bad. There are exceptions to this one, especially when designed something that interface with an external system. But, it’s very important to ask whether the dependence can be removed by either restructuring the input parameters, restructuring functions, or both. The problem with sequential dependence when it comes to maintenance is that it hurts code readability, and locks it any changes to external dependencies. So ask yourself twice if there is a better way if you find a set of function like this.
Sometimes it’s better to not refactor a function out unless it stand on its own. But be sure to remember that the person that comes behind you, which is usually you 6 months from now who has totally forgotten everything, won’t know your ideology while they absorb it purpose. So do yourself, and them a favor by writing code which speaks to them rather than having to be strangle out.