Object Oriented ProgrammingUnit 1012 min read
Structured vs. OOP: Paradigms, Principles & Practical Choices
Unit 10 of Object Oriented Programming compares procedural (structured) and object-oriented paradigms, highlighting their core principles, design trade-offs, and real-world applications in Nepalese software (eSewa, Daraz) and global systems (Google Maps). Includes visual comparisons, code examples, and exam-focused ana
TAKEAWAYS:
- Paradigm clash: Structured programming focuses on functions and data separation, while OOP bundles data + behavior into objects (classes).
- Key OOP advantages: Reusability (inheritance), modularity (encapsulation), and scalability (polymorphism) solve problems structured code struggles with (e.g., Daraz’s order management).
- Real-world tie: eSewa’s payment system uses OOP for user accounts (objects) with methods like
processTransaction(), while NTC’s billing might use structured functions for linear calculations. - When to choose: Use structured for simple, linear tasks (e.g., NEPSE stock calculators); OOP for complex systems with evolving requirements (e.g., Pathao’s ride-matching).
- Exam focus: Compare paradigms via 4 pillars of OOP (encapsulation, inheritance, polymorphism, abstraction) and contrast with structured programming’s modularity and top-down design.
- Code insight: Operator overloading (OOP) vs. function overloading (structured) for the same task (e.g., adding distances in feet/inches).
1. Core Definitions: Structured vs. OOP
Structured Programming (Procedural Paradigm)
- Definition: A programming approach where programs are divided into functions/procedures that operate on global data. Focuses on sequential, modular, and hierarchical code.
- Key Principles:
- Top-down design: Break problems into smaller functions (e.g.,
calculateTax(),validateInput()). - Data hiding: Achieved via access specifiers (e.g.,
privatein C), but not enforced by language. - Modularity: Functions are reusable but operate on shared data (risk of side effects).
- Top-down design: Break problems into smaller functions (e.g.,
Object-Oriented Programming (OOP)
- Definition: Programs are modeled as a collection of objects (instances of classes) that encapsulate data + behavior. Focuses on abstraction, modularity, and reusability.
- Key Principles (4 Pillars):
- Encapsulation: Bundling data (attributes) and methods (functions) into a single unit (class), with controlled access.
- Inheritance: Reuse code via hierarchical relationships (e.g.,
Animal→Dog). - Polymorphism: Same interface, multiple forms (e.g.,
+operator forintvs.string). - Abstraction: Hide complexity (e.g.,
BankAccount.withdraw()hides ATM logic).
2. Visual Comparison: Code Structures
Structured Approach (C-style)
flowchart TD
A["Main Function"] --> B["validateInput()"]
A --> C["calculateTax()"]
A --> D["displayResult()"]
B --> E["Global variables: taxRate, income"]
C --> E
D --> EExample: NTC’s billing system might use a main() with functions like computeBill() and printReceipt(), all operating on global arrays for customer data.
OOP Approach (C++/Java-style)
classDiagram
class Customer {
-name: string
-billAmount: double
+computeBill(): void
+printReceipt(): void
}
class NTCBillingSystem {
-customers: Customer[]
+processPayment(customer: Customer): bool
}
NTCBillingSystem --> Customer: "has-a"Example: eSewa’s payment system models each transaction as a Payment object with methods like validate() and process().
3. Real-World Applications in Nepal
OOP in Action
| System | OOP Concept Used | How It Works |
|---|---|---|
| eSewa | Encapsulation + Polymorphism | User class encapsulates balance and transactionHistory. Polymorphic Payment objects handle UPI, card, or mobile top-ups. |
| Daraz | Inheritance + Abstraction | Product (base class) → Electronics, Clothing (derived). Order abstract class defines process() for different payment methods. |
| Pathao | Objects for Dynamic States | Ride objects track status (e.g., "accepted," "in-progress") and update UI via methods like updateLocation(). |
| NEPSE | Operator Overloading | Stock class overloads + to add quantity (e.g., stock1 + stock2 merges holdings). |
Structured in Action
- NTC’s Legacy Systems: Uses functions like
calculateTax(globalCustomerData)for linear billing. No objects; data is passed via arrays. - Bank Loan Calculators: Procedural functions compute EMI (e.g.,
float calculateEMI(float principal, float rate)) without bundling data/behavior.
4. Worked Example: Order Management
Structured Approach (C-style)
#include <stdio.h>
#define MAX_ORDERS 100
typedef struct {
int id;
float price;
} Order;
void processOrder(Order orders[], int count) {
for (int i = 0; i < count; i++) {
if (orders[i].price > 1000) {
printf("Discount applied to order %d\n", orders[i].id);
}
}
}
int main() {
Order orders[MAX_ORDERS] = {{1, 1200}, {2, 800}};
processOrder(orders, 2);
return 0;
}
Trace:
| Step | orders[0] |
orders[1] |
Output |
|---|---|---|---|
| 1 | {1, 1200} |
{2, 800} |
"Discount applied to order 1" |
| 2 | (No output for order 2) |
Problem: Data (orders) and logic (processOrder) are separate. Adding a new field (e.g., customerName) requires changing all functions.
OOP Approach (C++)
#include <iostream>
#include <vector>
using namespace std;
class Order {
private:
int id;
float price;
public:
Order(int id, float price) : id(id), price(price) {}
void applyDiscount() {
if (price > 1000) cout << "Discount applied to order " << id << endl;
}
};
int main() {
vector<Order> orders = {Order(1, 1200), Order(2, 800)};
for (auto& order : orders) order.applyDiscount();
return 0;
}
Trace:
| Step | orders[0] Object State |
orders[1] Object State |
Output |
|---|---|---|---|
| 1 | id=1, price=1200 |
id=2, price=800 |
"Discount applied to order 1" |
| 2 | (No output for order 2) |
Advantages:
- Encapsulation:
priceis hidden; modified via methods (e.g.,setPrice()). - Extensibility: Add
customerNametoOrderclass without breaking existing code. - Reusability:
applyDiscount()can be reused in other classes (e.g.,PremiumOrder).
5. When to Use Which Paradigm
| Criteria | Structured Programming | Object-Oriented Programming |
|---|---|---|
| Problem Complexity | Simple, linear tasks (e.g., calculators) | Complex, evolving systems (e.g., Daraz’s inventory) |
| Code Reusability | Low (functions operate on global data) | High (inheritance, polymorphism) |
| Maintainability | Hard (changes ripple through functions) | Easy (localized changes to classes) |
| Performance | Slightly faster (no object overhead) | Slower for simple tasks (but negligible in modern systems) |
| Team Collaboration | Hard (shared global state) | Easy (objects encapsulate state) |
| Example in Nepal | NTC’s billing scripts | eSewa’s user management system |
6. Operator Overloading: Structured vs. OOP
Structured (Function Overloading)
float addDistances(float feet1, float inch1, float feet2, float inch2) {
float total1 = feet1 * 12 + inch1;
float total2 = feet2 * 12 + inch2;
return (total1 + total2) / 12;
}
Limitation: Requires explicit function calls and conversions.
OOP (Operator Overloading)
class Distance {
private:
float feet, inch;
public:
Distance(float f, float i) : feet(f), inch(i) {}
Distance operator+(Distance d) {
float total1 = feet * 12 + inch;
float total2 = d.feet * 12 + d.inch;
return Distance((total1 + total2) / 12, (total1 + total2) % 12);
}
};
int main() {
Distance d1(3, 6), d2(2, 8);
Distance d3 = d1 + d2; // Uses overloaded +
return 0;
}
Trace:
| Step | d1 State |
d2 State |
d3 State (Result) |
|---|---|---|---|
| 1 | feet=3, inch=6 |
feet=2, inch=8 |
feet=6, inch=2 (3’6” + 2’8” = 6’2”) |
Why OOP Wins:
- Intuitive syntax:
d1 + d2reads like natural language. - Extensible: Overload
<<forcout << d1to print distances.
7. Exam Tip: How to Score Full Marks
Compare via 4 Pillars:
- Always contrast structured programming’s modularity (functions) with OOP’s encapsulation (objects).
- Example answer snippet:
"Structured programming uses top-down design with functions like
validateOrder(), while OOP encapsulates validation logic within anOrderclass’sisValid()method, reducing global dependencies."
Use Real-World Analogies:
- Structured: "Like a restaurant kitchen where chefs (functions) work on shared ingredients (global data)."
- OOP: "Like a restaurant where each table (object) has its own order pad (methods) and bill (data)."
Code Examples:
- For questions on type conversion, show both:
- Structured:
float celsiusToFahrenheit(float c) { return (c * 9/5) + 32; } - OOP: Overload
operator float()in aTemperatureclass.
- Structured:
- For questions on type conversion, show both:
Diagrams:
- Draw class hierarchies for inheritance questions (e.g.,
Vehicle→Car→SUV). - Show state diagrams for object lifecycles (e.g.,
Orderstates: "created" → "shipped" → "delivered").
- Draw class hierarchies for inheritance questions (e.g.,
Common Pitfalls:
- ❌ Don’t say "OOP is always better." Mention structured is faster for simple tasks.
- ❌ Avoid vague terms like "OOP is object-based." Clarify: "OOP includes inheritance/polymorphism; object-based languages (e.g., JavaScript) lack these."
8. Past Exam Questions Solved
Q: "Define class and object with suitable example. How members of class can be accessed?"
Answer:
- Class: A blueprint for objects. Example:
class BankAccount { private: // Encapsulation string accountHolder; float balance; public: void deposit(float amount) { balance += amount; } }; - Object: Instance of a class. Example:
BankAccount myAccount("John", 1000); - Accessing Members:
- Public: Directly via dot operator (e.g.,
myAccount.deposit(500)). - Private: Accessed via public methods (e.g.,
myAccount.getBalance()).
- Public: Directly via dot operator (e.g.,
Visual:
classDiagram
class BankAccount {
-accountHolder: string
-balance: float
+deposit(amount: float): void
+getBalance(): float
}
BankAccount "1" --> "1" myAccount: "has"Q: "How object-oriented programming differs from object-based programming language?"
Answer:
| Feature | OOP (e.g., C++, Java) | Object-Based (e.g., JavaScript, VBScript) |
|---|---|---|
| Inheritance | Supported (e.g., class Dog extends Animal) |
Not supported |
| Polymorphism | Supported (method overriding/overloading) | Limited (no method overriding) |
| Encapsulation | Strong (private/public access) | Weak (no strict access modifiers) |
| Example in Nepal | Ncell’s billing system (inherits Customer → PremiumCustomer) |
Daraz’s cart system (objects but no inheritance) |
9. Key Takeaways for Exams
- Memorize the 4 Pillars: Encapsulation, inheritance, polymorphism, abstraction. Always link them to examples (e.g., "Pathao uses polymorphism for
Paymentobjects"). - Contrast Tables: Draw a table comparing structured vs. OOP for modularity, reusability, and maintainability.
- Code Traces: For operator overloading, show before/after states of objects (like the
Distanceexample above). - Real-World Links: Tie every concept to Nepalese systems:
- Encapsulation: eSewa hides user passwords.
- Inheritance: Daraz’s
Producthierarchy. - Polymorphism: NEPSE’s
Tradeobjects for different stock types.
Based on the TU BSc CSIT syllabus for Object Oriented Programming (CSC166), unit 10.
Discussion
Loading…