DEV Community

Discussion on: To Split or Not to Split

Collapse
 
jdforsythe profile image
Jeremy Forsythe

Splitting of functions is an art. It should always reduce duplication, isolate logic, or improve readability.

In my experience, most young devs get the first option wrong, making utility functions which end up being more complicated than just having something duplicated. Doing the same thing 2 or 3 times isn't enough of a reason to create an abstraction.

Isolating logic is a great reason to extract part of a function and lends itself well to pure functions, easy testing, and enhanced readability. I'm in complete agreement with what I think you're saying - one function should be handling the "state" and passing off data to pure functions for calculations, using their return values to update the state.

When the details of a group of statements isn't important for understanding what a function is doing, it can be beneficial to extract that to a separate function. This enhances readability of the main function and can be self-documenting, assuming good function/variable names.

As a general guideline, if I have to vertically scroll to read a function body, I will check to see if something can be extracted. But be careful not to make this an arbitrary rule that absolutely has to be followed. Only do it when it makes sense and provides on of the benefits listed above.