Lesson 3

Refactoring with OOP: Enhancing Code Readability

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 — 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.

1student_name = "Alice" 2student_age = 20 3student_grade = 3.9 4 5def display_student_info(): 6 print(f"Student Name: {student_name}") 7 print(f"Student Age: {student_age}") 8 print(f"Student Grade: {student_grade}") 9 10def update_student_grade(new_grade): 11 global student_grade 12 student_grade = new_grade

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

1class Student: 2 def __init__(self, name, age, grade): 3 self.name = name 4 self.age = age 5 self.grade = grade 6 7 def display_student_info(self): 8 print(f"Student Name: {self.name}") 9 print(f"Student Age: {self.age}") 10 print(f"Student Grade: {self.grade}") 11 12 def update_student_grade(self, new_grade): 13 self.grade = new_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:

1def calculate_gpa(grades): 2 total_points = 0 3 grade_points = {'A': 4, 'B': 3, 'C': 2, 'D': 1, 'F': 0} 4 for grade in grades: 5 total_points += grade_points[grade] 6 gpa = total_points / len(grades) 7 return gpa

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

1class Student: 2 def __init__(self, name, grades): 3 self.name = name 4 self.grades = grades 5 self.gpa = self.calculate_gpa() 6 7 def calculate_gpa(self): 8 total_points = 0 9 grade_points = {'A': 4, 'B': 3, 'C': 2, 'D': 1, 'F': 0} 10 for grade in self.grades: 11 total_points += grade_points[grade] 12 return total_points / len(self.grades)

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

Polymorphism to Cater for Multiple Behaviors

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:

1class Rectangle: 2 def draw_rectangle(self): 3 print("Drawing a rectangle.") 4 5class Triangle: 6 def draw_triangle(self): 7 print("Drawing a triangle.")

We have different method names for each class. We can refactor this to have a singular 'draw' method common to all shapes:

1class Shape: 2 def draw(self): 3 pass 4 5class Rectangle(Shape): 6 def draw(self): 7 print("Drawing a rectangle.") 8 9class Triangle(Shape): 10 def draw(self): 11 print("Drawing a triangle.")

Now, regardless of the shape of the object, we can use draw() to trigger the appropriate drawing behavior, thus enhancing flexibility.

Building Better Structure with Composition

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.

1class Window: 2 def __init__(self): 3 self.content = "Default content" 4 5 def add_text_field(self, content): 6 self.content = content 7 8 def display(self): 9 print(f"Window displays: {self.content}")

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.

Refactoring 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.

1class ContentManager: 2 def __init__(self, content="Default content"): 3 self.content = content 4 5 def update_content(self, new_content): 6 self.content = new_content 7 8 def get_content(self): 9 return self.content 10 11class Window: 12 def __init__(self): 13 self.manager = ContentManager() 14 15 def display(self): 16 print(f"Window displays: {self.manager.get_content()}") 17 18 def change_content(self, new_content): 19 self.manager.update_content(new_content)

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!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.