Instantiating new object vs. implementing a reset() method
Asked Answered
G

1

5

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?

Gladwin answered 9/4, 2017 at 15:24 Comment(0)
C
7

Generally, creating a new object and letting garbage collector destroy it is not expensive, unless this is done lots of times in a very tight loop. If you do that once per hand in a game, you wouldn't be able to measure the difference.

Therefore, it's best to concentrate on the most logical way to express your design to human readers of your code while deciding whether you should implement a reset() method or not:

  • If HandOfPoker is never shared among multiple objects, not using reset() has a cleaner appearance to readers of your code, because they don't need to look inside reset() to see what's going on.
  • If HandOfPoker is shared among multiple objects, e.g. for displaying, for persistence, etc., then it is better to have a reset() rather than setting the new object in multiple places.
Correa answered 9/4, 2017 at 15:34 Comment(1)
In addition, resetting requires explicit re-initialization of fields, while fields of new objects are already initialized to 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

© 2022 - 2024 — McMap. All rights reserved.