Avoiding multiple if conditions in a Car class In this dummy structure, we have a race car manager class. this class contains a method named execute().  There is a List which contains all participating racing cars.

This is the Car class, the List's type is based off:

public Car {

    private boolean driverBeltOn;
    private boolean engineOn;

    public boolean engineReady() {
        return this.engineOn;
    }

    public boolean driverBeltOn() {
        return this.driverBeltOn;
    }

    public void warn(String message) {
        // Send warning to car
        // ....
        // .....  (&lt;;D&gt;-&lt;;
        // ......
    }
}


The job of the execute method, is to loop through all cars, and make sure they are ready for the race, but if at-least one of the two conditions is false, then the car will not  participate in the race. 

If one condition is false, then the car should be notified, about why it can't participate.

Basic solution:

public void execute() {
    for (Car car : carList) {
        if (car.engineOn()) {
            if (car.driverBeltOn()) {
                // Can go..
            }
            else {
                car.warn("Please wear a damn belt!");
            }
        }
        else {
            car.warn("How are you planning to participate in a race with an off engine??");
        }
    }
}


What is the best way to handle things like this, where you have to check multiple conditions, and each condition should do something if it's false in the check?

Example of a bad solution, because it's impossible to let the car know what's wrong:

public void execute() {
    for (Car car : carList) {
        if (car.engineOn() &amp;&amp; car.driverBeltOn()) {
            // Can go..
        }
        else {
            car.warn("Something went wrong...");
        }
    }
}


Unless you add multiple checks inside the else block, which could be double work/bad practice.

What is the best practice do handle this? Or if inside if for this case is totally fine?
If you don't want to return early (because you want to go through all checks to warn about all problems), then you can use a flag to keep track of any problems:

for (Car car : carList) {
    boolean goodToGo = true; 
    if (!car.engineOn()) {
        car.warn("How are you planning to participate in a race with an off engine??");
        goodToGo = false;
    }
    if (!car.driverBeltOn()) {
        car.warn("Please wear a damn belt!");
        goodToGo = false;
    }
    if (goodToGo) {
        // Vroooomm....
    }
}


Btw, I guess you forgot a return statement here:


public boolean driverBeltOn() {
    this.driverBeltOn;
}



And I recommend to rename your methods to isDriverBeltOn and isEngineReady, as it's a fairly common practice to prefix boolean getters with "is...".