AngularDebutant
AngularDebutant

Reputation: 1576

Typescript: Class members initialization vs setters and getters

I have the following code:

export class Myclass {
   private _someVal = 2;

   public get someVal() {
      return this._someVal;
   }

   public set someVal(val) {
      this._someVal = val;
   }
}

I am using this someVal in the template <span>{{ someVal }}</span>

The value is not changing.

Is there any difference between using setters getters and setters, or simply having let someVal = 2 and using it directly in the template?

Upvotes: 0

Views: 442

Answers (3)

Martin
Martin

Reputation: 16292

Within a class you don't use the let keyword.

In this case there is no point in using accessors. If you trigger an action on set, or compute the value on get, then it makes sense to use them.

If accessing the property directly works, it is probably the right solution.

It is common in the Java world to create getters/setters for each field in a DTOs, it is arguable whether this is an anti-pattern. This practice leaks into other languages.

Rule of thumb: if you don't need an accessor, use a property.

Upvotes: 1

Matheus Cassol
Matheus Cassol

Reputation: 51

The only difference is that the get/set implementation allows you to have more flexibility, while the public property would be less flexible.

Example of what you could do with get:

export class Myclass {
   private _someVal = 2;
   private _otherVal = 1;

   public get calculatedVal() {
      return this._someVal + this._otherVal;
   }
}

And then access calculatedVal as a property like this: <span>{{ calculatedVal}}</span>

Upvotes: 1

bryan60
bryan60

Reputation: 29335

in this particular case there is no difference between what you've done and doing:

export class Myclass {
   someVal = 2;

}

setters and getters have use cases, such as when you need to do something else when setting a value, but this isn't one of them.

Upvotes: 2

Related Questions