Procedural vs Object-Oriented Programming: Same Program, Two Ways
What is the difference between procedural and object-oriented programming?
Procedural programming organises code as a sequence of functions that take data in and pass results on. Object-oriented programming bundles data and the functions that act on it into objects. Both can solve the same problems; procedural code is often simpler for small, linear tasks, while OOP scales better when many related things carry their own state and rules.
Key terms: paradigm, state and side effects
- Paradigm: a style of structuring programs. Procedural, object-oriented and functional are the three most common.
- Procedure (function): a named block of steps that can take arguments and return a value.
- State: data that a program remembers and changes over time, such as a basket total.
- Side effect: anything a function does beyond returning a value, such as printing, writing a file or changing a global variable.
- Pure function: a function whose result depends only on its arguments and which has no side effects.
Most modern languages, including Python, PHP and JavaScript, are multi-paradigm: you can mix styles in one project. The concepts behind the object-oriented side are explained in our introduction to OOP.
The task: a student marks report
Both versions below read a list of students with their marks, work out each average, assign a grade (A from 85, B from 70, C from 50, otherwise F) and print a report. The output is the same either way.
Asha 85.00 A
Ravi 54.67 C
Meera 91.00 A Version 1: procedural
Data lives in plain dictionaries; separate functions transform it step by step.
students = [
{"name": "Asha", "marks": [78, 85, 92]},
{"name": "Ravi", "marks": [55, 61, 48]},
{"name": "Meera", "marks": [90, 88, 95]},
]
def average(marks: list[int]) -> float:
return sum(marks) / len(marks) if marks else 0.0
def grade(avg: float) -> str:
if avg >= 85:
return "A"
if avg >= 70:
return "B"
if avg >= 50:
return "C"
return "F"
def print_report(records: list[dict]) -> None:
for record in records:
avg = average(record["marks"])
print(f"{record['name']:<7} {avg:6.2f} {grade(avg)}")
print_report(students)This is short and easy to follow from top to bottom. The weakness appears as the program grows: every function must know the dictionary keys, and nothing stops other code adding a mark of 150 or misspelling "marks".
Version 2: object-oriented
Now each student is an object that knows how to calculate its own average and grade, and a Report object handles output.
from dataclasses import dataclass, field
@dataclass
class Student:
name: str
marks: list[int] = field(default_factory=list)
def add_mark(self, mark: int) -> None:
if not 0 <= mark <= 100:
raise ValueError("Mark must be between 0 and 100")
self.marks.append(mark)
def average(self) -> float:
return sum(self.marks) / len(self.marks) if self.marks else 0.0
def grade(self) -> str:
avg = self.average()
for cutoff, letter in ((85, "A"), (70, "B"), (50, "C")):
if avg >= cutoff:
return letter
return "F"
class Report:
def __init__(self, students: list[Student]) -> None:
self.students = students
def show(self) -> None:
for s in self.students:
print(f"{s.name:<7} {s.average():6.2f} {s.grade()}")
Report([
Student("Asha", [78, 85, 92]),
Student("Ravi", [55, 61, 48]),
Student("Meera", [90, 88, 95]),
]).show()The code is longer, but the rules now sit with the data. Adding attendance, a CSV export or a web view means adding methods or a new report class without touching the grading logic. The dataclass decorator, covered in our object-oriented Python guide, writes the constructor for you.
A third option: functional style
Functional programming builds programs from pure functions and avoids changing data in place. Python supports this style with comprehensions, map(), filter(), sorted() with a key, and functools. Reusing the procedural average() function:
ranked = sorted(students, key=lambda s: average(s["marks"]), reverse=True)
print([s["name"] for s in ranked]) # ['Meera', 'Asha', 'Ravi']
print([s["name"] for s in students if average(s["marks"]) >= 70]) # ['Asha', 'Meera']Pure functions are easy to test because the same input always gives the same output. Many teams use OOP for structure and a functional style inside methods. Writing small, focused functions is covered in our Python functions guide.
Trade-offs and when to use which
| Factor | Procedural | Object-oriented |
|---|---|---|
| Size of program | Scripts and small tools | Applications with many related parts |
| Learning curve | Lower; fewer concepts | Higher; classes, interfaces, design choices |
| Where rules live | Spread across functions | Kept with the data they protect |
| Changing behaviour | Edit functions and every caller | Add a class that implements an interface |
| Risk | Shared global state grows tangled | Over-engineering with needless classes |
- Choose procedural for automation scripts, data clean-up jobs and short command-line tools.
- Choose OOP when you model real things with state, such as users, orders and invoices, or when several people will maintain the code for years.
- Use a functional style for data transformations, where each step takes a collection and returns a new one.
Practical exercise: rewrite a shopping basket both ways
- Write a procedural script that stores basket items as dictionaries with name, price and quantity, and has functions to add an item, remove an item and print the total.
- Rewrite it with an
Itemdataclass and aBasketclass whose methods refuse a negative quantity. - Add a 10% discount code to each version and note how many places you had to edit.
- Write one pure function that returns the three most expensive items without changing the basket.
You are done when both versions print the same total and you can explain which one was easier to extend. The PHP Foundation course practises both styles in PHP projects.
Common mistakes
- Wrapping every function in a class with no state, which adds ceremony without any benefit.
- Letting procedural scripts depend on many global variables that any function can change.
- Assuming OOP code is automatically better organised, even when classes have unclear responsibilities.
- Mixing styles randomly within one module, so readers cannot predict where logic lives.
Frequently asked questions
Is PHP procedural or object-oriented?
Both. PHP began as a procedural language and added full OOP support over time. Modern frameworks are object-oriented, while small scripts and many older WordPress themes are largely procedural.
Is Python an object-oriented language?
Everything in Python is an object, but you are not forced to write classes. You can write procedural, object-oriented or functional Python, and most real projects combine them.
Is functional programming the same as procedural programming?
No. Both use functions, but procedural code commonly changes shared state step by step, while functional code favours pure functions that return new values instead of modifying existing ones.