Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce code bloat in C from error handling & debugs [duplicate]

Consider this function:

int get_result(int *result) {
     int err = 0;
     int number = 0;         

     if (result == NULL) {
         printf("error: null input\n");
         return -1;
     }

     err = get_number(&number);

     if (err != 0) {
         printf("error calling get_number: err = %d\n", err);
         return err;
     }

     err = calculate_result(number, result);

     if (err != 0) {
        printf("error calling get_result: err = %d\n", err);
        return err;
     }

     return err;
}

The real work in this function requires only 3 lines (declare number variable, call get_number(), then call calculate_result()). However, the error checking/handling code bloats this function to 17 lines (give or take, depending on how you count the lines).

At a larger scale, with many calls, and multiple error checks, we bloat the function entirely and make it unreadable and very hard to understand.

What are ways to get around this bloating in C code and maintain readability of the core operation of a function (without sacrificing essential error handling code)?

like image 499
Akeel Avatar asked Aug 22 '15 16:08

Akeel


1 Answers

Welcome to the world of production quality code. There are some macro and factoring tricks that can make error checking less verbose. Exceptions are another mechanism. But the main adjustment to make is point of view. You are thinking of "the real work" as something separate from error handling. It's not. Dealing with all possible conditions is the essence of software engineering. To get it out of your system, explain "the main work" in comments, then write the real algorithm with externally imposed condition handling front and center.

like image 60
Gene Avatar answered Oct 22 '22 04:10

Gene