dimanche 27 septembre 2020

How to get rid of state or dependencies to simple reason

I have a class that has internal state and public getters:

function Section() {

  let ls = ['a','b','c','d','e','f'];
  let i = 0;

  this.map = () => ls[i];

  this.changeI = () => i=(i+1)%ls.length;

}

I have a user of this class:

function Ground() {

    let mover = new Mover(this);

    let map;

    this.map = () => map;

    this.init = () => {
        map = section.map();
    };


    this.draw = () => {
      console.log(map);
    }
}

and user of that class:

function Mover(ground) {

  let map = ground.map;


  this.dojob = () => {
    let usemap = map

    return usemap + 'X';
  }
}

Now when I call changeI, the return of the map function changes so I need to update the variable I use to draw the map in Ground function. I can make it a getter function instead of a variable as Mover class uses, but I think there is something wrong with this approach, I mean is there a better way to do this, or can I get rid of this internal state or the nested dependencies? I need an answer as simple as few abstractions as possible.

Aucun commentaire:

Enregistrer un commentaire