Skip to content

Code readability: Use early return/continue/break #1008

Description

@hoffie

Is your feature request related to a problem? Please describe.
Jamulus code currently has places with large levels of nesting/indentation. This is hard to read and follow through.
Example: https://github.com/jamulussoftware/jamulus/blob/master/src/audiomixerboard.cpp#L1138

The example has 7 levels of indentation which requires cognitive load to remember which level is what (a function, a for loop, an if).

Describe the solution you'd like
I propose usage of early continue/break (in loops) and return (in functions). This eases cognitive load.

Shortened, reworked code from the example:

void CAudioMixerBoard::ApplyNewConClientList ( CVector<CChannelInfo>& vecChanInfo )
{
    // get number of connected clients
    const int iNumConnectedClients = vecChanInfo.Size();

    Mutex.lock();
    {
        // we want to set the server name only if the very first faders appear
        // in the audio mixer board to show a "try to connect" before
        if ( bNoFaderVisible )
        {
            UpdateTitle();
        }

        // search for channels with are already present and preserve their gain
        // setting, for all other channels reset gain
        for ( int i = 0; i < MAX_NUM_CHANNELS; i++ )
        {
            bool bFaderIsUsed = false;

            for ( int j = 0; j < iNumConnectedClients; j++ )
            {
                // check if current fader is used
                if ( vecChanInfo[j].iChanID != i )
                {
                    continue; // <-- It's about this pattern
                }
// ...

I propose changing code in places where it is most relevant and places which are touched anyway.
I'm not suggesting that the whole codebase must be changed right now. I'm merely evaluating if PRs which do this would be accepted.

Describe alternatives you've considered
Keep things as they are.

Additional context
https://softwareengineering.stackexchange.com/questions/18454/should-i-return-from-a-function-early-or-use-an-if-statement
https://danp.net/2015/11/02/reducing-go-nesting.html
https://medium.com/better-programming/are-early-returns-any-good-eed4b4d03866

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions