Code Quality – Balancing Code Structuring: Few Big Functions vs. Many Small Ones

Architectureclass-designcode-quality

The golden rule of code structuring is always said as splitting into many sub functions is a good thing. Though I noticed it becomes a problem in complex applications when a class of e.g. 10 bigger functions is split into a class with 50 functions. When development went so far, it becomes quite hard to understand the concept of the class, I mean you lose survey. This is often the case when you look into code of others or in your own code after some months past.

I've heard a function should not be bigger than what fits on the screen. And then you start to split into sub functions, and the following effect is a class of many functions where you lose survey.

One example: The Qt library internally uses private classes, which means every class has a d pointer to a private object of its own private class containing all those helper functions moved out to it.

Sometimes I also wished I could colour the background of the important code.

So what's your approach of keeping complex code structured but still understandable?

Best Answer

The canonical answer is to apply the Single Responsibility principle:

the single responsibility principle states that every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.

Also, classes must have Cohesion

cohesion refers to the degree to which the elements of a module belong together. Thus, it is a measure of how strongly-related each piece of functionality expressed by the source code of a software module is

On the other hands, symptoms of low cohesion are exactly what you describe:

Disadvantages of low cohesion (or “weak cohesion”) are:

  • Increased difficulty in understanding modules.
  • Increased difficulty in maintaining a system, because logical changes in the domain affect multiple modules, and because changes in one module require changes in related modules.
  • Increased difficulty in reusing a module because most applications won’t need the random set of operations provided by a module.

As such, my advice is to review your class structure and refactor appropriately. You don't need to have very large classes, but certainly you want classes that do one clear thing right.

Related Topic