jeudi 3 octobre 2019

Wrap model with logic in Angular

Is it good practice to wrap model with logic into separate class?

For example we can have:

@Component({...})
export class SomeComponent {
  // lots of code
  public isSkyBlue: boolean;
  public isSunYellow: boolean;
  public isFridayToday: boolean;

  setAllToTrue() {
    this.isSkyBlue = true;
    this.isSunYellow = true;
    this.isFridayToday= true;
  }

  setAllToFalse() {
    this.isSkyBlue = false;
    this.isSunYellow = false;
    this.isFridayToday= false;
  }

  checkIfAtLeastOneIsTrue() {
    return this.isSkyBlue || this.isSunYellow || this.isFridayToday;
  }

  // lots of code
}

In this case we can create separate class that contains all this properties/logic and use like:

let settings = new Settings();
console.log(settings.checkIfAtLeastOneIsTrue());

It decreases amount of code in component and service and provides more intuitive usage.

But wouldn't it be antipattern? Often people say that it is not a good practice to mix model class and logic.

In the first Angular we had Factories for such cases. But in Angular 2-8 we don't have such abstraction. It may imply either to use just classes or not to wrap such cases and use only services.

Aucun commentaire:

Enregistrer un commentaire