lundi 12 novembre 2018

One instance with input passed as a parameter to methods vs Multiple instances with input passed as state to the constructor

Which solution is better in the following scenario and why?

I have a base class Level and multiple classes extending it. This class has multiple methods which will perform some business logic based on the state of a Player instance, or even modify the Player instance. This class sits on a Spring backend server and will serve multiple users, so the Player instance that will get passed into the Level class will be different per each request.

The initial design was to make the Level class have a thread scope, so only one instance will exist per thread. The reasoning for this is that the Level class will be called once for Player1.State1, do the business logic and then immediately be called for Player2.StateX, do the same business logic but with the different state, and then maybe at some point be called for Player1.State2, so basically a different state again (even though it is the same Player1 as previously in regards to the playerId). So it didn't make sense to me to create an instance for every request and pass the Player in the constructor (set it as the Level state and then reuse it in the business logic methods) because it will be a lot of wasted memory for what would be 'Single use instances' (since I will not reuse the same instance for a future request).

However, as I was writing the BL methods I realised the design was looking really bad, from a visual point of view to begin with. Because I was passing the Player instance to every single method instead of keeping it in a field and pass it in the constructor. But this way I will have to create a new Level instance every time...

So which one is better from a Design vs Memory/Performance trade off?

Solution1

class Level {
  public void DoSomething1(Player player) {// use player in BL}
  public void DoSomething2(Player player) {// use player in BL}
  ..
  public void DoSomething10(Player player) {// use player in BL}
}

Level level = new Level() // gets called only once per thread and reused for every request

Solution2

class Level {
  Player player;
  public Level(Player player) {
    this.player = player;
  }

  public void DoSomething1() {// use this.player in BL}
  public void DoSomething2() {// use this.player in BL}
  ..
  public void DoSomething10() {// use this.player in BL}
}

Level level = new Level(player) // gets called every time for each request

Aucun commentaire:

Enregistrer un commentaire