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!
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.
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.
Kotlin1var studentName = "Alice" 2var studentAge = 20 3var studentGrade = 3.9 4 5fun displayStudentInfo() { 6 println("Student Name: $studentName") 7 println("Student Age: $studentAge") 8 println("Student Grade: $studentGrade") 9} 10 11fun updateStudentGrade(newGrade: Double) { 12 studentGrade = newGrade 13}
Although functional, the code could cause potential confusion as the related attributes and behaviors aren't logically grouped. Let's encapsulate!
Kotlin1class Student( 2 private var name: String, 3 private var age: Int, 4 private var grade: Double 5) { 6 7 fun displayStudentInfo() { 8 println("Student Name: $name") 9 println("Student Age: $age") 10 println("Student Grade: $grade") 11 } 12 13 fun updateStudentGrade(newGrade: Double) { 14 grade = newGrade 15 } 16 17 // Getters for name, age, and grade 18 fun getName() = name 19 fun setName(name: String) { this.name = name } 20 21 fun getAge() = age 22 fun setAge(age: Int) { this.age = age } 23 24 fun getGrade() = grade 25 fun setGrade(grade: Double) { this.grade = grade } 26}
After refactoring, all student-related properties and methods are contained within the Student
class, thereby enhancing readability and maintainability.
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:
Kotlin1fun calculateGpa(grades: Array<String>): Double { 2 var totalPoints = 0 3 val gradePoints = mapOf("A" to 4, "B" to 3, "C" to 2, "D" to 1, "F" to 0) 4 for (grade in grades) { 5 totalPoints += gradePoints[grade] ?: 0 6 } 7 return totalPoints.toDouble() / grades.size 8}
We can encapsulate this within the calculateGpa()
method of our Student
class, thereby simplifying the interaction.
Kotlin1class Student( 2 private var name: String, 3 private var grades: Array<String> 4) { 5 private var gpa: Double = calculateGpa() 6 7 private fun calculateGpa(): Double { 8 var totalPoints = 0 9 val gradePoints = mapOf("A" to 4, "B" to 3, "C" to 2, "D" to 1, "F" to 0) 10 for (grade in grades) { 11 totalPoints += gradePoints[grade] ?: 0 12 } 13 return totalPoints.toDouble() / grades.size 14 } 15 16 fun getName() = name 17 fun setName(name: String) { this.name = name } 18 19 fun getGrades() = grades 20 fun setGrades(grades: Array<String>) { 21 this.grades = grades 22 this.gpa = calculateGpa() 23 } 24 25 fun getGpa() = gpa 26}
We can now access the gpa
as an attribute of the student object, which is calculated behind the scenes.
Polymorphism provides a unified interface for different types of actions, making our code more flexible.
Assume we are developing a simple graphics editor. Here is a code snippet without polymorphism:
Kotlin1class Rectangle { 2 fun drawRectangle() { 3 println("Drawing a rectangle.") 4 } 5} 6 7class Triangle { 8 fun drawTriangle() { 9 println("Drawing a triangle.") 10 } 11}
We have different method names for each class. We can refactor this to have a singular draw
method common to all shapes:
Kotlin1abstract class Shape { 2 abstract fun draw() 3} 4 5class Rectangle : Shape() { 6 override fun draw() { 7 println("Drawing a rectangle.") 8 } 9} 10 11class Triangle : Shape() { 12 override fun draw() { 13 println("Drawing a triangle.") 14 } 15}
Now, regardless of the shape of the object, we can use draw()
to trigger the appropriate drawing behavior, thus enhancing flexibility.
Our last destination is Composition, which models relationships between objects and classes. Composition allows us to design our systems in a flexible and maintainable way by constructing complex objects from simpler ones. This principle helps us manage relationships by ensuring that objects are composed of other objects, thus organizing dependencies more neatly and making individual parts easier to update or replace.
Consider a system in our application that deals with rendering various UI elements. Initially, we might have a Window
class that includes methods both for displaying the window and managing content like buttons and text fields directly within it.
Kotlin1class Window { 2 private var content: String = "Default content" 3 4 fun addTextField(content: String) { 5 this.content = content 6 } 7 8 fun display() { 9 println("Window displays: $content") 10 } 11}
This approach tightly couples the window display logic with the content management, making changes and maintenance harder as we add more elements and functionalities. Let's now see how we can update this code with composition.
To implement Composition, we decouple the responsibilities by creating separate classes for content management (ContentManager
) and then integrating these into our Window
class. This way, each class focuses on a single responsibility.
Kotlin1class ContentManager { 2 private var content: String = "Default content" 3 4 fun updateContent(newContent: String) { 5 this.content = newContent 6 } 7 8 fun getContent() = content 9} 10 11class Window { 12 private val manager: ContentManager = ContentManager() 13 14 fun display() { 15 println("Window displays: ${manager.getContent()}") 16 } 17 18 fun changeContent(newContent: String) { 19 manager.updateContent(newContent) 20 } 21}
By refactoring with Composition, we've encapsulated the content management within its class. The Window
class now "has a" ContentManager
, focusing on displaying the window. This separation allows for easier modifications in how content is managed or displayed without altering the other's logic. Composition, in this way, enhances our system's flexibility and maintainability by fostering a cleaner and more modular design.
Great job! We've learned how to apply OOP principles to refactor code for improved readability, maintainability, and scalability.
Now, get ready for some exciting exercises. Nothing strengthens a concept better than practice! Happy refactoring!