Home > Software engineering >  What is the difference, if any, between field value and property in TypeScript/Angular?
What is the difference, if any, between field value and property in TypeScript/Angular?

Time:01-25

In this example, I have two cases of a service that exposes an observable, test$. One through a getter, the other as a public field.

Is there any practical difference?

I have seen numerous examples of declarative programming using the field way. Is using a getter not considered declarative?

component:

@Component()
export const TestComp {
    private test$ = this.testService.test$; 
    constructor(private testService: TestService){}
}

Case 1: Service with field value:

@Injectable()
export const TestService {
    public test$ = of('test');
}

Case 2: Service with property/getter:

@Injectable()
export const TestService {

    private _test$ = of('test');
    public get test$() {
        return this._test$;
    }
}

CodePudding user response:

The following are the advantages I can think of for using getters/setters

  1. Adding appropriate access specifiers and validation logic before retrieving the property of the object.

  2. Avoiding Anemic domain model. This is to make sure classes that describes domain has its own logic and validations instead of services handling all of the business logic.

A bit more reading on Anemic domain model https://en.wikipedia.org/wiki/Anemic_domain_model

CodePudding user response:

I would say it is a matter of convinience and less boilerplate code.

For example

interface Service{
  readonly name:String;
}

class Service1 implements Service{
  constructor(public readonly name:string){
  }
}

class Service2 implements Service{
  private _name:string;
  get name():string{
    return this.name;
  }
//   some wat to set/mutate name internally - ctor/method
}

Bot implementations correctly implements Service declaration and it does not matter to the consumer which implementation is used. So in you case, it just a matter of preferences of the author

  • Related