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:
JavaScript1var student_name = "Alice"; 2var student_age = 20; 3var student_grade = 3.9; 4 5function displayStudentInfo() { 6 console.log("Student Name: " + student_name); 7 console.log("Student Age: " + student_age); 8 console.log("Student Grade: " + student_grade); 9} 10 11function updateStudentGrade(new_grade) { 12 student_grade = new_grade; 13}
Although functional, the code could cause potential confusion as the related attributes and behaviors aren't logically grouped. Let's encapsulate!
JavaScript1class Student { 2 constructor(name, age, grade) { 3 this.name = name; 4 this.age = age; 5 this.grade = grade; 6 } 7 8 displayStudentInfo() { 9 console.log("Student Name: " + this.name); 10 console.log("Student Age: " + this.age); 11 console.log("Student Grade: " + this.grade); 12 } 13 14 updateStudentGrade(newGrade) { 15 this.grade = newGrade; 16 } 17}
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:
JavaScript1function calculateGpa(grades) { 2 var totalPoints = 0; 3 var gradePoints = {'A': 4, 'B': 3, 'C': 2, 'D': 1, 'F': 0}; 4 grades.forEach(function(grade) { 5 totalPoints += gradePoints[grade]; 6 }); 7 var gpa = totalPoints / grades.length; 8 return gpa; 9}
We can encapsulate this within the calculateGpa()
method of our Student
class, thereby simplifying the interaction.
JavaScript1class Student { 2 constructor(name, grades) { 3 this.name = name; 4 this.grades = grades; 5 this.gpa = this.calculateGpa(); 6 } 7 8 calculateGpa() { 9 var totalPoints = 0; 10 var gradePoints = {'A': 4, 'B': 3, 'C': 2, 'D': 1, 'F': 0}; 11 this.grades.forEach((grade) => { 12 totalPoints += gradePoints[grade]; 13 }); 14 return totalPoints / this.grades.length; 15 } 16}
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:
JavaScript1class Rectangle { 2 drawRectangle() { 3 console.log("Drawing a rectangle."); 4 } 5} 6 7class Triangle { 8 drawTriangle() { 9 console.log("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:
JavaScript1class Shape { 2 draw() { 3 throw new Error("This method should be overridden by subclasses"); 4 } 5} 6 7class Rectangle extends Shape { 8 draw() { 9 console.log("Drawing a rectangle."); 10 } 11} 12 13class Triangle extends Shape { 14 draw() { 15 console.log("Drawing a triangle."); 16 } 17}
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 flexibly and maintainably 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.
JavaScript1class Window { 2 constructor() { 3 this.content = "Default content"; 4 } 5 6 addTextField(content) { 7 this.content = content; 8 } 9 10 display() { 11 console.log("Window displays: " + this.content); 12 } 13}
This approach tightly couples the window's 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.
JavaScript1class ContentManager { 2 constructor(content = "Default content") { 3 this.content = content; 4 } 5 6 updateContent(newContent) { 7 this.content = newContent; 8 } 9 10 getContent() { 11 return this.content; 12 } 13} 14 15class Window { 16 constructor() { 17 this.manager = new ContentManager(); 18 } 19 20 display() { 21 console.log("Window displays: " + this.manager.getContent()); 22 } 23 24 changeContent(newContent) { 25 this.manager.updateContent(newContent); 26 } 27}
By refactoring with Composition, we've encapsulated the content management within its own 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!