vendredi 6 novembre 2015

If the execution of the bulk of a function is conditional on the input, which of these is a better way to implement?

I'm wondering which of these is better and why. I often encounter situations in my daily work where I'm like "This algorithm works so long as the input isn't empty" or something like that. I usually just return early because, for some reason, the idea of wrapping almost the entirety of a function in an if conditions seem wrong to me. However, I know that some religions don't believe in early return statements.

Example:

(1)

function combine ( strings , separator )
{
    if ( strings.length > 0 )
    {
       retstring = strings[0];
       for ( var i = 1; i < strings.length; ++ i )
           retstring += (separator + strings[i]);
    }
    return retstring;
}

(2)

function combine ( strings , separator )
{
    if (strings.length === 0) return undefined;   
     retstrings =  strings[0];
     for ( var i = 1; i < strings.length; ++ i )
         retstring += (separator + strings[i]);   
     return retstring;
}

So which is better to go with in such situations?

Aucun commentaire:

Enregistrer un commentaire