Introduction and Lesson Overview

Hello once again! Today's lesson is centered around leveraging the principles of Object-Oriented Programming (OOP) — Encapsulation, Abstraction, Polymorphism, and Composition — using TypeScript to enhance code readability and structure. Buckle up for an exciting journey ahead!

Connection between OOP and Code Refactoring

OOP principles act as a scaffold for building readable, maintainable, and flexible code — these are the characteristics we seek while refactoring. By creating logical groupings of properties and behaviors in classes, we foster a codebase that's easier to comprehend and modify. Let's put this into perspective as we progress.

Applying Encapsulation for Better Code Organization

Encapsulation involves bundling related properties and methods within a class, thereby creating an organization that mirrors the real world.

Suppose we possess scattered student information within our program:

let studentName: string = "Alice";
let studentAge: number = 20;
let studentGrade: number = 3.9;

function displayStudentInfo(): void {
  console.log("Student Name: " + studentName);
  console.log("Student Age: " + studentAge);
  console.log("Student Grade: " + studentGrade);
}

function updateStudentGrade(newGrade: number): void {
  studentGrade = newGrade;
}

Although functional, the code could cause potential confusion since the related attributes and behaviors aren't logically grouped. Let's encapsulate!

class Student {
  private name: string;
  private age: number;
  private grade: number;

  constructor(name: string, age: number, grade: number) {
    this.name = name;
    this.age = age;
    this.grade = grade;
  }

  public displayStudentInfo(): void {
    console.log("Student Name: " + this.name);
    console.log("Student Age: " + this.age);
    console.log("Student Grade: " + this.grade);
  }

  public updateStudentGrade(newGrade: number): void {
    if (newGrade >= 0 && newGrade <= 4.0) {
      this.grade = newGrade;
    } else {
      console.log("Invalid grade. Please provide a value between 0 and 4.0.");
    }
  }
}

Access Modifiers: In the refactored class, the name, age, and grade properties are marked as private, ensuring they cannot be accessed or modified directly from outside the class. Instead, controlled access is provided via public methods (displayStudentInfo and updateStudentGrade).

Validation Logic: The updateStudentGrade method includes basic validation to ensure grades fall within a valid range. This further demonstrates how encapsulation helps maintain data integrity.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal