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.

var studentName = "Alice"
var studentAge = 20
var studentGrade = 3.9

fun displayStudentInfo() {
    println("Student Name: $studentName")
    println("Student Age: $studentAge")
    println("Student Grade: $studentGrade")
}

fun updateStudentGrade(newGrade: Double) {
    studentGrade = newGrade
}

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

class Student(
    private var name: String, 
    private var age: Int, 
    private var grade: Double
) {

    fun displayStudentInfo() {
        println("Student Name: $name")
        println("Student Age: $age")
        println("Student Grade: $grade")
    }

    fun updateStudentGrade(newGrade: Double) {
        grade = newGrade
    }
    
    // Getters for name, age, and grade
    fun getName() = name
    fun setName(name: String) { this.name = name }
    
    fun getAge() = age
    fun setAge(age: Int) { this.age = age }
    
    fun getGrade() = grade
    fun setGrade(grade: Double) { this.grade = grade }
}

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

Utilizing Abstraction to Simplify Code Interaction

Next up is Abstraction. It is about exposing the relevant features and concealing the complexities.

Consider a code snippet calculating a student's grade point average (GPA) through complex operations:

fun calculateGpa(grades: Array<String>): Double {
    var totalPoints = 0
    val gradePoints = mapOf("A" to 4, "B" to 3, "C" to 2, "D" to 1, "F" to 0)
    for (grade in grades) {
        totalPoints += gradePoints[grade] ?: 0
    }
    return totalPoints.toDouble() / grades.size
}

We can encapsulate this within the calculateGpa() method of our Student class, thereby simplifying the interaction.

class Student(
    private var name: String, 
    private var grades: Array<String>
) {
    private var gpa: Double = calculateGpa()

    private fun calculateGpa(): Double {
        var totalPoints = 0
        val gradePoints = mapOf("A" to 4, "B" to 3, "C" to 2, "D" to 1, "F" to 0)
        for (grade in grades) {
            totalPoints += gradePoints[grade] ?: 0
        }
        return totalPoints.toDouble() / grades.size
    }

    fun getName() = name
    fun setName(name: String) { this.name = name }

    fun getGrades() = grades
    fun setGrades(grades: Array<String>) {
        this.grades = grades
        this.gpa = calculateGpa()
    }

    fun getGpa() = gpa
}

We can now access the gpa as an attribute of the student object, which is calculated behind the scenes.

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