1

I'm rather new to programming and Java specifically. I'm currently building a game with a Ship object. It has the following data members;

int START_M_ENERGY = 21;
int START_C_ENERGY = 1;
int STARTING_HEALTH = 5;
int maximalEnergyLevel = STARTING_MAX_ENERGY;
int currentEnergyLevel = STARTING_CURRENT_ENERGY;

The code also has a 'death' method. This method basically resets all of these data members back to their original values (as they change during the game). The method basically looks exactly like the code above. So, is this considered 'duplicate code'? Is there a way to avoid it? (We're not allowed to use abstract classes or something yet, not sure if it's related but i've seen the subject pop up). Important to note, the SpaceShip class has no constructor because I think initializing these as members make sense. Will calling the constructor upon death make sense? I don't want the object to be replaced upon death, only resetted! Thanks!

Omri. B
  • 375
  • 1
  • 13

2 Answers2

2

Resetting the values is fine and I would not consider it repeated code unless you assign the same values to these members in another place. Don't invoke the constructor if you want to keep the same object upon death.

1

I think initializing these as members make sense

It could make sense, but there are better ideas.

Stil you can override constructor with no arguments. Then you can call death() method inside it.

public SpaceShip() {
    death();
}

death() {
    this.maximalEnergyLevel = STARTING_MAX_ENERGY; //or use setter
    this.currentEnergyLevel = STARTING_CURRENT_ENERGY; //or use setter
}

I guess START_M_ENERGY and other UPPERCASE variables are constants, if is that true - mark them as static final, if not - add to death() method and use camelCase. Then you can consider change the method name to "reset()".

B_Osipiuk
  • 888
  • 7
  • 16