Interview Questions, Answers and Tutorials

Refactoring procedural code to object-oriented code

Refactoring procedural code to object-oriented code

Hey there! Today, we’re going to learn about a cool way to organize our code. Think of your code like a big box of LEGO bricks. When it’s all messy, it’s hard to find the pieces you need. But if you organize them by color and shape, it’s much easier to build something amazing! In programming, we can similarly organize our code by using Object-Oriented Programming (OOP). This helps us make our code easier to read, use, and manage.

What is Procedural Code?

Procedural code is like following a recipe. You do things step by step, one after the other. Let’s say you want to bake a cake. You would:

  1. Mix the ingredients.
  2. Pour the batter into a pan.
  3. Bake the cake.
  4. Let it cool.

In procedural programming, we write our code like this:

# Mixing ingredients
ingredients = ["flour", "sugar", "eggs", "butter"]
batter = "mixed"

# Pouring the batter into a pan
pan = "filled with batter"

# Baking the cake
oven = "baking"
cake = "baked"

# Letting it cool
cake = "cool"




This works, but it can get messy when our recipes (programs) get longer and more complex.

What is Object-Oriented Programming (OOP)?

OOP is like organizing our LEGO bricks. Instead of doing everything step by step, we group related actions. We create objects that have properties (things they are) and methods (things they do).

Imagine you have a LEGO box labeled “Car.” Inside, you have all the pieces you need to build a car, and you know what the car can do (drive, honk, etc.).

In OOP, we use classes to create objects. A class is like a blueprint for our LEGO car. It tells us what pieces we need and what the car can do.

Refactoring Procedural Code to OOP

Let’s take our cake-baking example and turn it into OOP.

  1. Identify the Objects: First, we need to figure out what our objects are. In our cake example, we might have an Cake object.
  2. Define the Class: Next, we create a class for our object. This class will have properties (like ingredients) and methods (like mix, bake, cool).

Here’s how we can do it:

Procedural Code
# Mixing ingredients
ingredients = ["flour", "sugar", "eggs", "butter"]
batter = "mixed"

# Pouring the batter into a pan
pan = "filled with batter"

# Baking the cake
oven = "baking"
cake = "baked"

# Letting it cool
cake = "cool"




Refactored to OOP
class Cake:
    def __init__(self):
        self.ingredients = ["flour", "sugar", "eggs", "butter"]
        self.batter = None
        self.baked = False
        self.cool = False

    def mix(self):
        self.batter = "mixed"
        print("Ingredients mixed.")

    def pour_into_pan(self):
        if self.batter == "mixed":
            print("Batter poured into pan.")
        else:
            print("You need to mix the ingredients first.")

    def bake(self):
        if self.batter == "mixed":
            self.baked = True
            print("Cake baked.")
        else:
            print("You need to pour the batter into the pan first.")

    def let_cool(self):
        if self.baked:
            self.cool = True
            print("Cake cooled.")
        else:
            print("You need to bake the cake first.")

# Using the Cake class
my_cake = Cake()
my_cake.mix()
my_cake.pour_into_pan()
my_cake.bake()
my_cake.let_cool()




Now, our cake-baking process is organized inside a Cake class. This makes it easier to manage, especially if we want to bake many cakes or add more steps.

Practice Questions

  1. Refactor a Simple Program: Here’s a small program that calculates the area of a rectangle:
width = 5
height = 10
area = width * height
print("The area of the rectangle is", area)

Refactor it using a Rectangle class.

  1. Create a Car Class: Create a class for a car. The class should have properties like color, make, and model, and methods like start_engine, drive, and stop_engine.

Solutions

  1. Refactor a Simple Program:

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def calculate_area(self):
        return self.width * self.height

my_rectangle = Rectangle(5, 10)
area = my_rectangle.calculate_area()
print("The area of the rectangle is", area)

  1. Create a Car Class:
class Car:
    def __init__(self, color, make, model):
        self.color = color
        self.make = make
        self.model = model
        self.engine_running = False

    def start_engine(self):
        self.engine_running = True
        print(f"The {self.color} {self.make} {self.model}'s engine started.")

    def drive(self):
        if self.engine_running:
            print(f"The {self.color} {self.make} {self.model} is driving.")
        else:
            print("Start the engine first.")

    def stop_engine(self):
        self.engine_running = False
        print(f"The {self.color} {self.make} {self.model}'s engine stopped.")

my_car = Car("red", "Toyota", "Corolla")
my_car.start_engine()
my_car.drive()
my_car.stop_engine()

By refactoring our procedural code into object-oriented code, we organize our code better, making it easier to understand, reuse, and maintain. It’s like turning a messy LEGO pile into neatly organized sets, ready to build anything you imagine!