Function C is called only once and cyclic complexity

I think this question is more about style: I have an algorithm that has a very high CC (and lots of lines!). I want to reduce it, and this is easy, because there are pieces of code that can be grouped. The problem is that I make it so that I will have a "large" function that calls the "small" functions, which are called only once.

In my opinion, breaking a large function into small pieces is better for readability of the code (in this case), despite the fact that functions are called once.

What are you doing? How do you do in such cases?

+4
source share
4 answers

Breaking a large function into smaller, mostly individual pieces is a great idea. This makes the code more readable and the control flow more understandable.

If the functions are static and are called only once, the compiler will probably embed them for you without even asking, so there is no need to worry about the cost of execution.

+7
source

There is nothing wrong with functions that are called only once. They keep your code in order and you don’t lose anything, just add function calls, there is no real performance improvement for functions that you call only once.

+3
source

Going beyond the built-in functions, there are many functions that are called only once.

Let's say we have a structure like this:

typedef struct foo { char *foo; int bar; double foobar; } foo_t; 

And we write something to initialize / highlight:

 foo_t *foome(void) { foo_t *ret; ret = (foo_t *) malloc(sizeof(struct foo)); ... ... } 

But why did we survive this whole problem when foome() is called only once, in main() ? Because we want the next person to deal with our program in order to be able to look at main() and immediately understand what we are trying to accomplish.

I would prefer to see code that has dozens of one-time functions, if that means that a complex algorithm is read like a book on one (or close) screen. I can’t say how much my head hurts when I have to scroll up and down a hundred lines trying to save my place.

This saves sanity and helps the environment, because now I do not need to print all 60 pages of your algorithm and place them on the table to read it :)

+2
source

As already mentioned, dividing a large function into several smaller ones has many advantages. Readability (with the correct name), grouping of local variables (temporary functions used in functions are closer to each other, which gives a better cache behavior), it may happen that one of these functions can be reused elsewhere, a thing that previously was not visible.

0
source

Source: https://habr.com/ru/post/1310505/


All Articles