0% found this document useful (0 votes)
1 views6 pages

Programming styles

The document compares Object-Oriented Programming (OOP) and Structured Programming, highlighting OOP's flexibility in modifying programs through encapsulated objects, while structured programming requires more cumbersome modifications. It illustrates the differences using examples of BankAccount implementations in C and Python, emphasizing OOP's ease of adding functionality and managing data. Additionally, it discusses how objects in OOP interact through method calls, contrasting with the procedural approach of passing data between functions.

Uploaded by

Erdey Syoum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views6 pages

Programming styles

The document compares Object-Oriented Programming (OOP) and Structured Programming, highlighting OOP's flexibility in modifying programs through encapsulated objects, while structured programming requires more cumbersome modifications. It illustrates the differences using examples of BankAccount implementations in C and Python, emphasizing OOP's ease of adding functionality and managing data. Additionally, it discusses how objects in OOP interact through method calls, contrasting with the procedural approach of passing data between functions.

Uploaded by

Erdey Syoum
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

In OOP, the ability to modify a program by declaring new classes and adding new methods without

radically altering the previously debugged program is one of the key benefits that distinguishes it from
Structured Programming. To understand this better, let’s compare the two paradigms in terms of
modification flexibility and how they handle changes in the system.

Adding data and functions in procedural language is relatively difficult when we compare with object
oriented languages. In procedural programming, adding new data and related functions often requires
modifying multiple sections of code and possibly duplicating or rearranging existing logic. In contrast,
object-oriented programming (OOP) encapsulates data and related functions within objects, making it
easier to extend and maintain.

Python needs to keep track of certain pieces of data that change over time as a program runs (like which
variables exist and what their values are, what has been printed to the screen, etc). We call this
information the program state.

so in oop we start at individual objects and we combine the individual objects to solve a problem but in
structure we start at main and from there we call subprocedures to solve a problem I got it?

Exactly! In OOP (Object-Oriented Programming), you start by designing objects that interact with each
other. Each object represents a real-world entity with its own attributes (data) and behaviors (methods).
You then combine these objects to build the overall system.

In structured programming, on the other hand, you start with a main function and break the problem
into smaller procedures (functions) that execute in a logical sequence.

So, OOP is bottom-up (building from objects), while structured programming is top-down (starting with
main and breaking down tasks). You nailed it!

BankAccount in C (Procedural Approach)

In C, we use structures to define data, but we can’t directly associate functions with data. Functions are
implemented separately and take the structure as a parameter to operate on it.

#include <stdio.h>

typedef struct {

char owner[50];

double balance;

} BankAccount;

// Function to deposit money

void deposit(BankAccount *account, double amount) {


account->balance += amount;

// Function to withdraw money

void withdraw(BankAccount *account, double amount) {

if (account->balance >= amount) {

account->balance -= amount;

} else {

printf("Insufficient funds\n");

// Function to calculate interest

double calculate_interest(BankAccount *account, double rate) {

return account->balance * rate / 100;

int main() {

// First Bank Account

BankAccount account1 = {"Alice", 1000.0};

deposit(&account1, 200.0);

withdraw(&account1, 100.0);

printf("Account 1 Balance: %.2f\n", account1.balance);

printf("Account 1 Interest (5%%): %.2f\n", calculate_interest(&account1, 5.0));

// Second Bank Account

BankAccount account2 = {"Bob", 500.0};

deposit(&account2, 300.0);

withdraw(&account2, 150.0);

printf("Account 2 Balance: %.2f\n", account2.balance);

printf("Account 2 Interest (5%%): %.2f\n", calculate_interest(&account2, 5.0));


return 0;

Explanation:

Structure: BankAccount is a structure that holds the owner and balance.

Functions: Functions like deposit, withdraw, and calculate_interest are separate, and we pass a pointer
to BankAccount as a parameter.

Modularity: To add another account, we must create another BankAccount structure and call each
function with a pointer to the specific account.

BankAccount in Python (Object-Oriented Approach)

In Python, we define a BankAccount class that encapsulates both the data (attributes) and behaviors
(methods). Each account can be created as an instance of the class.

class BankAccount:

def __init__(self, owner, balance=0.0):

self.owner = owner

self.balance = balance

def deposit(self, amount):

self.balance += amount

def withdraw(self, amount):

if self.balance >= amount:

self.balance -= amount

else:

print("Insufficient funds")

def calculate_interest(self, rate):

return self.balance * rate / 100


# Example usage

account = BankAccount("Alice", 1000)

account.deposit(200)

account.withdraw(100)

print(f"Balance: {account.balance}")

print(f"Interest (5%): {account.calculate_interest(5)}")

Explanation:

Class: BankAccount is a class, meaning both data (e.g., owner and balance) and functions (e.g., deposit,
withdraw, and calculate_interest) are encapsulated within the class.

Instance Methods: Methods like deposit and withdraw act directly on the instance (self), allowing us to
manipulate data associated with the instance without needing global variables or external pointers.

Creating Accounts: New accounts are created by instantiating BankAccount, making it simple to handle
multiple accounts and additional functionalities if required.

Summary of Key Differences

In C: Functions are separate, requiring manual management of data pointers, making code more verbose
and less modular.

In Python: The object-oriented approach encapsulates data and behavior together, so adding
functionality or new instances of BankAccount is much easier and more scalable.

In object-oriented programming (OOP), objects interact by sending messages to each other,


which can be thought of as calling methods or passing data between them. To illustrate this
concept, here’s a simple example using Python:

Scenario: Bank Account Interaction

Let's say we have a BankAccount class with objects representing individual accounts. Each
account can receive messages (method calls) like deposit, withdraw, and transfer. When an
account transfers money to another, it sends a message to the recipient object.

python
Copy code
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
# Process: Increases balance
self.balance += amount
print(f"{self.owner} deposited ${amount}. New balance: $
{self.balance}")

def withdraw(self, amount):


# Process: Checks balance and decreases if sufficient
if amount <= self.balance:
self.balance -= amount
print(f"{self.owner} withdrew ${amount}. New balance: $
{self.balance}")
else:
print(f"{self.owner} attempted to withdraw ${amount}, but
insufficient funds!")

def transfer(self, amount, recipient_account):


# Message Sending: Calls the deposit method of another object
if amount <= self.balance:
self.withdraw(amount)
recipient_account.deposit(amount)
print(f"{self.owner} transferred ${amount} to
{recipient_account.owner}.")
else:
print(f"{self.owner} attempted a transfer of ${amount}, but
insufficient funds!")

# Create two account objects


alice_account = BankAccount("Alice", 500)
bob_account = BankAccount("Bob", 300)

# Alice sends a transfer message to Bob's account


alice_account.transfer(200, bob_account)

Explanation

 Objects Receiving Messages: alice_account and bob_account are objects receiving


messages through method calls. For example, alice_account.deposit(100) sends the
deposit message to Alice’s account.
 Processing Data: When alice_account.withdraw(50) is called, Alice’s account
checks if the balance is sufficient and processes the withdrawal by reducing her balance.
 Sending Messages to Other Objects: When Alice transfers money to Bob using
alice_account.transfer(200, bob_account), it calls bob_account.deposit(200),
sending a deposit message to Bob’s account.

Paradigims:

 Procedural programming is a programming paradigm that is based on procedures,


routines, or functions. These procedures are sets of instructions that perform a specific
task or job. In procedural programming, the program is typically structured around
procedures, and data is often manipulated by passing it between procedures.
 Structured Programming is a subset of procedural programming that enforces a
logical structure on the program being written to make it more efficient and easier to
understand and modify. It enforces a clear and well-defined structure using control
structures like sequences, selections (if-else), and iterations (loops). The key idea
behind structured programming is to break down a program into small, manageable
sections or blocks.

Consider the following example:


record Date {
int day
int month
int year
}

This defines a data structure for recording dates. There are similar structures in many
procedural languages such as C, Ada and Pascal. So, what is wrong with a structure such as this?
Nothing, apart from the issue of visibility? That is, what can see this structure and what can
update the contents of the structure? Any code can directly access and modify its contents. Is this
problem? It could be, for example, some code could set the day to -1, the month to 13 and the
year to 9999. As far as the structure is concerned the information it now holds is fine (that is day
= 01, month = 13, year = 9999). This is because the structure only knows it is supposed to hold
integers; it knows nothing about dates per se. This is not surprising; it is only data.
The problem is that the data is naked and has no defense against what these procedures do to it.
Indeed, it has no defense against what any procedures that can access it, may do to it.

You might also like