Refactoring the creation of a variable number of planets in Java

OneSurvivor :

I have to assign a random amount of objects in this program, and currently the only way I know to do this is something like this:

    if (star.returnZones() == 1) {
        this.createPlanet(planet1, star);
    }
    else if (star.returnZones() == 2) {
        this.createPlanet(planet1, star);
        this.createPlanet(planet2, star);
    }
    else if (star.returnZones() == 3) {
        this.createPlanet(planet1, star);
        this.createPlanet(planet2, star);
        this.createPlanet(planet3, star);
    }
    else if (star.returnZones() == 4) {
        this.createPlanet(planet1, star);
        this.createPlanet(planet2, star);
        this.createPlanet(planet3, star);
        this.createPlanet(planet4, star);
    }
    else if (star.returnZones() == 5) {
        this.createPlanet(planet1, star);
        this.createPlanet(planet2, star);
        this.createPlanet(planet3, star);
        this.createPlanet(planet4, star);
        this.createPlanet(planet5, star);
    }

I am sure this is a far more efficent way to do this, where each one does something along the lines of this. I will be using the term asAbovePlus to mean everything above, plus one more thing.

if (star.returnZones() == 1) {
    this.createPlanet(planet1, star);
}
else if (star.returnZones() == 2) {
    asAbovePlus
    this.createPlanet(planet2, star);
}

Is there a way to do something like this in Java? It would really help out.

njzk2 :

Start by removing the duplicates:

int zones = star.returnZones();
if (zones >= 1) {
    createPlanet(planet1, star);
}
if (zones >= 2) {
    createPlanet(planet2, star);
}
...

You can see that in the example where zones == 2, it does execute the 2 blocks, so you keep the same functionality.

Then, you can see that this is actually a loop. Start by putting the planets in an array:

Planet[] planets = new Planet[] {planet1, planet2, ...};
for (int i = 0; i < star.returnZones(); i++) {
    createPlanet(planets[i], star);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=420057&siteId=1