DEV Community

Jon Stødle
Jon Stødle

Posted on • Originally published at blog.jonstodle.com on

To Split or Not to Split

Some people encourage smaller functions rather than larger ones. “If a function does more than one thing, break it into smaller ones”, they say. Others say that breaking functions into smaller functions like that reduces readability. “Keep everything in one place if it belongs together. Don’t make me jump around the code to find out what’s happening”.

Personally, I’m leaning towards the first opinion. I feel calling smaller helper functions inside a larger one assists readability. The larger function describes the overall process, while the smaller ones abstract away the nitty gritty of each task, making the whole flow easier to read.

I think there’s an important point to make about these helper functions: I always keep them pure. I don’t want these helper functions to modify local state of any kind. They take some kind of input and return a result. That’s it.

I think some of the people who dislike splitting up functions would let helper functions mutate state, which I agree would create a lot of mess. By keeping the helper functions pure, I think this confusion is avoided.

Just a thought.

Happy coding!

Top comments (1)

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.