Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - What is better: Get / Set properties

Just recently discovered about using get and set keywords for class properties I was wondering what is the preferred method when using get / set for typescript classes:

class example {
    private a: any;
    private b: any;

    getA(): any{
        return this.a;
    }

    setA(value: any){
        this.a = value;
    }

    get b(): any{
        return this.b;
    }

    set b(value: any){
        this.b = value;
    }
}

I am just curious if there are any best practices, performance, or other factors.

like image 231
Jeremy Trpka Avatar asked Mar 01 '18 15:03

Jeremy Trpka


1 Answers

Getter and Setters have several uses, like

You can make a private variable read only, if you don't specify a setter

class example {
    private _a: any;

    get a(): any{
        return this._a;
    }
}

You can use them to execute a custom logic when a variable changes, sort of a replacement for Event Emitter

class example {
    private _a: any;

    set a(value: any){
        this._a = value;

        // Let the world know, I have changed
        this.someMethod();
    }

    someMethod() {
        // Possibly a POST API call
    }
}

You can use them to alias an output

class Hero {
    private _health: any = 90;

    get health(): string {
        if(this._health >= 50) {
            return "I am doing great!";
        } else {
            return "I don't think, I'll last any longer";
        }
    }
}

A setter can be used for a clean assignment

class Hero {
    private _a: number;

    set a(val: number) {
        this._a = val;
    }

    setA(val: number) {
        this._a = val;
    }

    constructor() {
        this.a = 30;    // Looks cleaner
        this.setA(50);  // Looks Shabby, Method's purpose is to perform a logic not handle just assignments
    }
}

Finally setter's biggest strength is the ability to check variables for proper value before assignment

class Hero {
    private _age: number;

    set age(age: number) {
        if (age > 0 && age < 100) {
            this._age = age
        } else {
            throw SomeError; 
        }
    }
}
like image 50
Abhijit Kar ツ Avatar answered Oct 08 '22 03:10

Abhijit Kar ツ