Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring the creation of a variable number of planets in Java

Tags:

java

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.

like image 830
OneSurvivor Avatar asked May 10 '17 19:05

OneSurvivor


1 Answers

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); } 
like image 127
njzk2 Avatar answered Sep 22 '22 07:09

njzk2