Lesson Overview

Hello once again! Today's lesson is centered around leveraging the principles of Object-Oriented Programming (OOP) — Encapsulation, Abstraction, Polymorphism, and Composition — 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.

String studentName = "Alice";
int studentAge = 20;
double studentGrade = 3.9;

public static void displayStudentInfo() {
    System.out.println("Student Name: " + studentName);
    System.out.println("Student Age: " + studentAge);
    System.out.println("Student Grade: " + studentGrade);
}

public static void updateStudentGrade(double newGrade) {
    studentGrade = newGrade;
}

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

public class Student {
    private String name;
    private int age;
    private double grade;

    public Student(String name, int age, double grade) {
        this.name = name;
        this.age = age;
        this.grade = grade;
    }

    public void displayStudentInfo() {
        System.out.println("Student Name: " + name);
        System.out.println("Student Age: " + age);
        System.out.println("Student Grade: " + grade);
    }

    public void updateStudentGrade(double newGrade) {
        this.grade = newGrade;
    }
    
    // Getters and Setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getGrade() {
        return grade;
    }

    public void setGrade(double grade) {
        this.grade = grade;
    }
}

After refactoring, all student-related properties and methods are contained within the Student class, thereby enhancing readability and maintainability.

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