Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Last active March 23, 2026 03:33
Show Gist options
  • Select an option

  • Save anushshukla/4186324583240aa53f565cbc06fd2f1a to your computer and use it in GitHub Desktop.

Select an option

Save anushshukla/4186324583240aa53f565cbc06fd2f1a to your computer and use it in GitHub Desktop.
Programming design principles

Object Oriented Programming Priciples

Encapsulation

Example

class Person {
    // full name is encapsulated as its a private member
    private _fullName: string;
    public fname: string;
    public lname: string;
    public constructor(fname: string, lname: string) {
        this.fname = fname;
        this.lname = lname;
        // encapsulate full name can only be updated by the class as its private
        // in this way full name will always be consistent with first & last name
        this._fullName = `${this.fname} ${this.lname}`;
    }
    // encapsulated full name is exposed through a public method
    public getFullName(): string {
        return this._fullName;
    }
}

const person = new Person('John', 'Smith');
console.log('Person full name is', person.getFullName());

Advantages

  • Data protection As per above example, the full name can't be mutated from outside as its a private member & internally derived from the class
  • Simpler maintenance As per above example, we don't need to maintain the full name as the class does it.
  • Human error reduction As per above example, as we are not computing the full name & the class is doing it on its own, hence a mistake in generating the full name is not possible if the first & last name are valid.

Abstraction

Example

class Person {
    // full name is encapsulated as its a private member
    private _fullName: string;
    public fname: string;
    public lname: string;
    public constructor(fname: string, lname: string) {
        this.fname = fname;
        this.lname = lname;
        // encapsulate full name can only be updated by the class as its private
        // in this way full name will always be consistent with first & last name
        this._fullName = `${this.fname} ${this.lname}`;
    }
    // encapsulated full name is exposed through a public method
    public getFullName(): string {
        return this._fullName;
    }
}

const person = new Person('John', 'Smith');
console.log('Person full name is', person.getFullName());

Advantages

  • Reduce complexity
  • Increase efficiency
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment