user499054
user499054

Reputation:

Is it okay to use functions to stay organized in C?

I'm a relatively new C programmer, and I've noticed that many conventions from other higher-level OOP languages don't exactly hold true on C.

Is it okay to use short functions to have your coding stay organized (even though it will likely be called only once)? An example of this would be 10-15 lines in something like void init_file(void), then calling it first in main().

Upvotes: 15

Views: 552

Answers (8)

DigitalRoss
DigitalRoss

Reputation: 146141

Yes


I follow a few guidelines:

  1. DRY (aka DIE)
  2. Keep Cyclomatic Complexity low
  3. Functions should fit in a Terminal window

Each one of these principles at some point will require that a function be broken up, although I suppose #2 could imply that two functions with straight-line code should be combined. It's somewhat more common to do what is called method extraction than actually splitting a function into a top and bottom half, because the usual reason is to extract common code to be called more than once.

#1 is quite useful as a decision aid. It's the same thing as saying, as I do, "never copy code".

#2 gives you a good reason to break up a function even if there is no repeated code. If the decision logic passes a certain complexity threshold, we break it up into more functions that make fewer decisions.

Upvotes: 1

L. Cornelius Dol
L. Cornelius Dol

Reputation: 64066

I would have to say, not only is it OK, but it's generally encouraged. Just don't overly fragment the train of thought by creating myriads of tiny functions. Try to ensure that each function performs a single cohesive, well... function, with a clean interface (too many parameters can be a hint that the function is performing work which is not sufficiently separate from it's caller).

Furthermore, well-named functions can serve to replace comments that would otherwise be needed. As well as providing re-use, functions can also (or instead) provide a means to organize the code and break it down into smaller units which can be more readily understood. Using functions in this way is very much like creating packages and classes/modules, though at a more fine-grained level.

Upvotes: 21

Robert Groves
Robert Groves

Reputation: 7748

If I can take the liberty to do some quoting from Code Complete:

(These reason details have been abbreviated and in spots paraphrased, for the full explanation see the complete text.)

Valid Reasons to Create a Routine

Note the reasons overlap and are not intended to be independent of each other.

  1. Reduce complexity - The single most important reason to create a routine is to reduce a program's complexity (hide away details so you don't need to think about them).

  2. Introduce an intermediate, understandable abstraction - Putting a section of code int o a well-named routine is one of the best ways to document its purpose.

  3. Avoid duplicate code - The most popular reason for creating a routine. Saves space and is easier to maintain (only have to check and/or modify one place).

  4. Hide sequences - It's a good idea to hide the order in which events happen to be processed.

  5. Hide pointer operations - Pointer operations tend to be hard to read and error prone. Isolating them into routines shifts focus to the intent of the operation instead of the mechanics of pointer manipulation.

  6. Improve portability - Use routines to isolate nonportable capabilities.

  7. Simplify complicated boolean tests - Putting complicated boolean tests into a function makes the code more readable because the details of the test are out of the way and a descriptive function name summarizes the purpose of the tests.

  8. Improve performance - You can optimize the code in one place instead of several.

  9. To ensure all routines are small? - No. With so many good reasons for putting code into a routine, this one is unnecessary. (This is the one thrown into the list to make sure you are paying attention!)

And one final quote from the text (Chapter 7: High-Quality Routines)

One of the strongest mental blocks to creating effective routines is a reluctance to create a simple routine for a simple purpose. Constructing a whole routine to contain two or three lines of code might seem like overkill, but experience shows how helpful a good small routine can be.

Upvotes: 8

farhanhubble
farhanhubble

Reputation: 494

It is indeed a good practice to refactor code into functions, irrespective of the language being used. Even if your code is short, it will make it more readable. If your function is quite short, you can consider inlining it.

IBM Publib article on inlining

Upvotes: 0

phoxis
phoxis

Reputation: 61950

Functions are absolutely necessary to stay organized. You need to first design the problem, and then depending on the different functionality you need to split them into functions. Some segment of code which is used multiple times, probably needs to be written in a function.

I think first thinking about what problem you have in hand, break down the components and for each component try writing a function. When writing the function see if there are some code segment doing the same thing, then break it into a sub function, or if there is a sub module then it is also a candidate for another function. But at some time this breaking job should stop, and it depends on you. Generally, do not make many too big functions and not many too small functions.

When construction the function please consider the design to have high cohesion and low coupling.

EDIT1::

you might want to also consider separate modules. For example if you need to use a stack or queue for some application. Make it separate modules whose functions could be called from other functions. This way you can save re-coding commonly used modules by programming them as a group of functions stored separately.

Upvotes: 4

i_am_jorf
i_am_jorf

Reputation: 54610

Yes. Please. Don't write long functions. Write short ones that do one thing and do it well. The fact that they may only be called once is fine. One benefit is that if you name your function well, you can avoid writing comments that will get out of sync with the code over time.

Upvotes: 16

Evan Teran
Evan Teran

Reputation: 90503

i think it is more than OK, I would recommend it! short easy to prove correct functions with well thought out names lead to code which is more self documenting than long complex functions.

Any compiler worth using will be able to inline these calls to generate efficient code if needed.

Upvotes: 5

Martin Beckett
Martin Beckett

Reputation: 96147

If a group of statements can be thought of as a thing - then make them a function

Upvotes: 5

Related Questions