Certainly! Below are examples of the same problem solved using Object-Oriented Programming (OOP) and Functional Programming (FP) in Python.
Problem:
Calculate the area and perimeter of a rectangle.
1. Object-Oriented Programming (OOP) Approach
In OOP, we define a Rectangle class with methods to compute area and perimeter.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
# Usage
rect = Rectangle(5, 10)
print("Area:", rect.area()) # Output: 50
print("Perimeter:", rect.perimeter()) # Output: 30
Key OOP Concepts Used:
- Encapsulation: Data (
width, height) and methods (area, perimeter) are bundled together.
- State: The
Rectangle object holds its own state (width, height).
- Methods: Functions are tied to the object.
2. Functional Programming (FP) Approach
In FP, we avoid mutable state and use pure functions to compute results.
def area(width, height):
return width * height
def perimeter(width, height):
return 2 * (width + height)
# Usage
width, height = 5, 10
print("Area:", area(width, height)) # Output: 50
print("Perimeter:", perimeter(width, height)) # Output: 30
Key FP Concepts Used:
- Pure Functions:
area() and perimeter() take inputs and return outputs without side effects.
- Immutability: No state is stored; calculations are done on input parameters.
- No Classes: Functions are independent and reusable.
Comparison Summary
| Feature | OOP (Class-Based) | FP (Function-Based) |
|---|
| State | Mutable (stored in objects) | Immutable (passed as arguments) |
| Functions | Methods (bound to objects) | Standalone functions |
| Reusability | Methods are tied to objects | Functions are independent |
| Side Effects | Possible (e.g., modifying object state) | Avoided (pure functions) |
| Example | rect.area() | area(width, height) |
When to Use Which?
- OOP is great for modeling real-world entities (e.g.,
User, BankAccount).
- FP is better for data transformations, mathematical computations, and avoiding side effects.
Python supports both paradigms, so you can mix them as needed! 🚀