I have the following setup:
public abstract class Entity {
public abstract void update();
}
public class Particle extends Entity {
// ...
}
public class Enemy extends Entity {
// ...
}
And I need to know the amount of Enemies every frame:
if (numEnemies > 50)
doSomething();
So, which of the following is a more suitable design?
Option 1:
List<Entity> enemies;
List<Entity> players;
// ...
int numEnemies = enemies.size();
for (Entity i : enemies)
i.update();
for (Entity i : players)
i.update();
Option 2:
List<Entity> entities;
int numEnemies = 0;
// ...
if (needMoreEnemies()) {
++numEnemies; // Keep a count and decrease on removal
entities.add(new Enemy());
}
for (Entity i : entities)
i.update();
Or something else entirely?
Option 2 is better. For even better OOP, the "needMoreEnemies" block should be put in the Enemy class, perhaps as a static method, or perhaps in the update method. This would allow for other classes to have "once-per-frame" checks.
And of course, instead of:
for (Entity i : entities)
i.update();
Use Java 8 style:
entities.stream().forEach(Entity::update);
If you never have to treat enemies and players separately, the second approach is better: keeping separate counts and treating objects polymorphically in all other situations is easier.
If, on the other hand, you sometimes need to segregate objects for separate treatment, you would be better off with the first approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With