Creating a new object versus implementing the reset () method
I am currently building a console game implementation of 5 card poker games in Java.
I have a class called HandOfCards that will handle the individual hand players' materials, their cards, bets, and winner determination. I also have a class called GameOfPoker that facilitates multiple poker hands by representing a complete poker experience.
I will create an instance of HandOfPoker for GameOfPoker as such:
HandOfPoker handOfPoker = new HandOfPoker(List<PokerPlayer> players, DeckOfCards deck);
My question is, in GameOfPoker, should I instantiate a new object or define a reset method in HandOfPoker:
public class HandOfPoker{
public void reset(List<PokerPlayer> players) {
this.players = players;
}
}
public class GameOfPoker{
public play() {
// carry out game
// then after a hand, I could either instantiate:
//handOfPoker = new HandOfPoker(players, deck);
// or I could reset:
handOfPoker.reset();
// now I'm ready to play another hand.
}
}
Intuitively, the reset () approach seems to be better - since instantiating a new object seems more costly, since a new instance must be instantiated and the old one must be broken.
Is there a best practice approach here, or is the difference between the two approaches small enough that it doesn't matter?
source to share
Generally, creating a new object and destroying the garbage collector is not expensive unless it is done many times in a very tight loop. If you do this once per hand in a game, you cannot measure the difference.
So it's best to focus on the most logical way to express your design to the readers of your code, deciding whether you should use the method reset()
or not:
- If it is
HandOfPoker
never shared across multiple objects, the usereset()
is cleaner for the readers of your code because they don't need to look insidereset()
to see what's going on. - If
HandOfPoker
shared between multiple objects, eg. for display, for saving, etc., it is better to havereset()
rather than set a new object in multiple places.
source to share