dimanche 12 mai 2019

Function structure: "if error, early return" or "if error, assign, else, assign, return assigned value"?

In the context of embedded systems, given the following function structures:

  1. Conditional assignement to return variable:

    int foo(int x)
    {
        int status;
    
        if (is_valid(x))
        {
            /* long computation with x */
            status = /* some result */;
        }
        else
            status = STATUS_ERROR;
    
        return status;
    }
    
    
  2. Early return:

    int foo(int x)
    {
        if (!is_valid(x))
            return STATUS_ERROR;
    
        /* long computation with x */
        return /* some result */;
    }
    
    

In my opinion, the latter should be preferred over the former as:

  • It doesn't require extra and unnecessary definition and assignments for status;
  • It clearly states to the reader that in case of an error, nothing is done except from returning STATUS_ERROR, which is written at the start of the function, in the clearest way the language permits;
  • It allows the code for the normal case to be flatter as it doesn't have to be indented for the if-else.

However, I have seen the former being used in a few different projects. I believe that the reasons for this might be related to the debugging step of development, to allow:

  • having a single point of return, allowing easier breakpoint placement;
  • inspection of the soon-to-be returned value through status (in particular at that single return).

Am I right in assuming that this is done for debugging? Are there other reasons to prefer 1. over 2.? Is 1. considered good practice in the context of baremetal development?

Please note that, unlike in this question, no work is done before returning the error code in case of an invalid x.

Aucun commentaire:

Enregistrer un commentaire