lundi 23 mars 2020

Better solution to avoid struggle with the property rename in a class

I created the following simple class

class Animal{
    constructor(feet) {
       this.feet = feet; //I mean paws.I think it should be in the prototype of subclass but here is an example
    }

  set feet(value){
    if(Number.isInteger(value) && value>0) {
       this._feet = value;
    }
    else {
      //Print a message report
      throw new Error('Invalid Initialization');
    }
  }

  get feet(){
    return this._feet;
  }

  static calcFeet(...animals)
  {
    return animals.reduce((prev,cur) => prev+cur.feet , 0);
  }

}

const an1 = new Animal(2);
const an2 = new Animal(4);

console.log(an1.feet); //2
console.log(an2.feet); //4
console.log(Animal.calcFeet(an1,an2)); //6

I have setter and getter to check integrity of the value for the property feet and an utility method on the constructor Animal. Everything nice but in this way if I would to change the name property feet in paws I should do it in several points of the code class definition. Thus I implemented an alternative version:

class Animal{
    constructor(paws) {
       this.setPaws(paws);
    }

    setPaws(paws){
      if(Number.isInteger(paws) && paws>0) {
        this.paws = paws;
      }
      else {
        //Print a message report
        throw new Error('Invalid Initialization');
      }
    }

  getPaws(){
    return this.paws;
  }

  static calcFeet(...animals)
  {
    return animals.reduce((prev,cur) => prev+cur.getPaws() , 0);
  }

}

const an1 = new Animal(2);
const an2 = new Animal(4);

console.log(an1.getPaws()); //2
console.log(an2.getPaws()); //4
console.log(Animal.calcFeet(an1,an2)); //6

I was wondering if the latest version is more correct than first both from software engineering point of view or from javascript style perspective. And if it isn't the case what could be a cleanest up implementation?

Aucun commentaire:

Enregistrer un commentaire