mercredi 29 mai 2019

Nested if-conditions vs multiple separated if-conditions with return statement in each one

What is the most professional code-style in the below two functions ?
And what if the function become more complex & larger such as to have 20 checks ?
Note: i need to do some stuff after each check, so i can't concatenate all in one if-statement like:
if (vehicle.isBus) && (vehicle.numberOfWheels == 6) && (vehicle.motorVersion == 2019)

//first alternative
public bool validate(Vehicle vehicle)
{
    if(vehicle.isBus)
    {
        //do some stuff here related to vehicle.isBus
        if (vehicle.numberOfWheels == 6)
        {
            //do some stuff here related to vehicle.numberOfWheels
            if (vehicle.motorVersion == 2019)
            {
                //do some stuff here related to vehicle.motorVersion
                return true;
            }
        }
    }
    return false;
}

//second alternative
public bool validate(Vehicle vehicle)
{
    if (!vehicle.isBus)
    {
        return false;
    }
    //do some stuff here related to vehicle.isBus

    if (vehicle.numberOfWheels != 6)
    {
        return false;
    }
    //do some stuff here related to vehicle.numberOfWheels

    if (vehicle.motorVersion != 2019)
    {
        return false;
    }
    //do some stuff here related to vehicle.motorVersion

    return true;
}

Aucun commentaire:

Enregistrer un commentaire