I'm currently creating a console implementation of a game of 5 card draw poker in Java.
I have a class called HandOfCards, which will handle the proceedings of an individual hand - dealing players their cards, betting and determining the winner. I also have a class called GameOfPoker which facilitates multiple hands of poker, representing the full sitting of a game of poker.
I will construct the HandOfPoker instance 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 should I 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, it feels like the reset() approach seems better - as to instantiate a new object seems more costly as a new instance has to be created, and the old one has to be trashed.
Is there a best practice approach here, or is the difference between the two approaches small enough that it doesn't really matter?
0
/false
/null
. If those values are good for a new instance, it may actually be more costly to manually reset fields, than to just create a new object. But, this is unnecessary micro-optimization, and should be avoided, i.e. don't consider it, but focus instead on program logic, as already said in this answer. – Tims