Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should polymorphic objects be updated in one list [closed]

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?

like image 228
Matthew D. Scholefield Avatar asked Sep 18 '26 22:09

Matthew D. Scholefield


2 Answers

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);
like image 82
Necreaux Avatar answered Sep 20 '26 13:09

Necreaux


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.

like image 45
Sergey Kalinichenko Avatar answered Sep 20 '26 13:09

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!