Back to series
· 9 min read

Procedural, Object-Oriented, and Functional Programming


I. What Is a Programming Paradigm?

A programming paradigm is a way of thinking and a method for organizing code, expressing computational logic, and designing program structure.

It determines how developers view a program, how they organize data, and how they describe the computational process.

The same business requirement can be implemented using different programming paradigms.

For example, suppose we need to build a bank account system that supports deposits, withdrawals, and balance inquiries.

What the different paradigms focus on:

  • Procedural Programming: focuses on which steps the business must go through and how each step is executed.
  • Object-Oriented Programming (OOP): focuses on which objects exist in the system and what responsibilities those objects bear.
  • Functional Programming (FP): focuses on how to obtain a result through function composition and data transformation.

These three are not mutually exclusive categories of languages; they are different approaches to program design.

Modern programming languages usually support multiple paradigms at the same time. For example:

Language Procedural Object-Oriented Functional
C Native support Can simulate some object ideas through structs and functions Can implement some functional techniques through function pointers
C++ Supported Native support Supports lambdas, function objects, etc.
Java Supported Native support Supports lambdas, Streams, etc.
Python Supported Native support Supports higher-order functions, closures, etc.
JavaScript Supported Prototype-based object model Supports higher-order functions, closures, etc.
Go Supported Organizes programs through structs, methods, and interfaces Supports closures and higher-order functions, but has no traditional class inheritance
Rust Supported Implements related designs through structs, enums, and traits Supports iterators, closures, and pattern matching

The point of understanding programming paradigms is not to memorize which category a language belongs to, but to grasp how different ways of thinking solve problems.

II. Procedural Programming

1. Core Idea

Procedural programming is centered on procedures and operational steps. It breaks a program into a series of functions or procedures, and completes business tasks by calling those procedures.

Its basic approach is:

  1. Analyze which operations the problem requires.
  2. Break the complex task into multiple steps.
  3. Encapsulate the steps as functions.
  4. Call the functions in business order.
  5. Pass and modify data through variables and data structures.

Procedural programming emphasizes the execution process of a program and usually adopts a top-down design approach.

2. Basic Structure

A procedural program usually consists of the following parts:

  • Data: stores the information the program needs to run.
  • Functions: encapsulate specific operations.
  • Control structures: determine the order in which the program executes.
  • Call relationships: organize collaboration among different functions.

For example, a bank account system can be broken down into:

  • Initialize the account.
  • Deposit.
  • Withdraw.
  • Check the balance.

3. Python Implementation Example

balance = 1000


def deposit(amount):
    global balance

    if amount <= 0:
        return False

    balance += amount
    return True


def withdraw(amount):
    global balance

    if amount <= 0 or amount > balance:
        return False

    balance -= amount
    return True


def get_balance():
    return balance


deposit(500)
withdraw(200)

print(get_balance())

Output:

1300

In the code:

  • balance stores the account balance.
  • deposit() handles deposits.
  • withdraw() handles withdrawals.
  • get_balance() handles balance inquiries.

Data and operations are organized separately, and the functions access and modify the account state through a shared variable.

4. Execution Structure of Procedural Programming

flowchart TB
    A["Bank Account Operations"] --> B["Initialize Account"]
    B --> C["Deposit"]
    C --> D["Withdraw"]
    D --> E["Check Balance"]
    E --> F["Output Result"]

    style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

5. Advantages of Procedural Programming

Intuitive structure

Programs are organized according to business steps, making the execution order easy to understand.

Lower implementation cost

For smaller programs with simple logic, development can be completed quickly.

Explicit execution control

Developers can directly control function calls, loops, conditionals, and state changes.

Suitable for process-oriented tasks

Examples include data transformation, batch processing, script automation, and simple algorithms.

6. Limitations of Procedural Programming

Data and operations are separated

Data is usually stored independently, and multiple functions may modify the same data.

Shared state can easily cause problems

As the number of functions increases, a change to data by one function may affect the execution results of other functions.

Higher maintenance cost for large systems

As business logic becomes more complex, the calls and dependencies between functions can become increasingly difficult to manage.

Responsibility boundaries are not clear enough

Without good module partitioning, different functions may take on too many responsibilities, leading to code coupling.

7. Applicable Scenarios

  • Small utility programs.
  • Automation scripts.
  • Data processing tasks.
  • Algorithm implementations.
  • Businesses with relatively fixed workflows.
  • Low-level programs that require explicit control over execution.

Note that procedural programming does not necessarily mean the code will be chaotic. Reasonable module partitioning, data encapsulation, and function responsibility design can also be used to build large procedural programs with a clear structure.

III. Object-Oriented Programming

1. Core Idea

Object-oriented programming centers on objects, organizes data and the behaviors that operate on the data together, and completes business tasks through collaboration among objects.

An object usually consists of two parts:

  • Attribute: Describes the state of an object.
  • Method: Describes the behaviors an object can perform.

For example, a bank account can be abstracted as an Account object:

  • Attributes: account number, account balance.
  • Methods: deposit, withdraw, and check balance.

Unlike procedural programming, which organizes data and operations separately, object-oriented programming emphasizes encapsulating related data and behavior inside an object.

2. Classes and Objects

In object-oriented programming, two basic concepts need to be understood.

Class

A class is an abstract definition of an object, used to describe what attributes and behaviors a type of object has.

Object

An object is a concrete instance of a class. It has its own state and can execute the methods defined by the class.

For example:

class Account:
    def __init__(self, balance=0):
        self.balance = balance

    def deposit(self, amount):
        if amount <= 0:
            return False

        self.balance += amount
        return True

    def withdraw(self, amount):
        if amount <= 0 or amount > self.balance:
            return False

        self.balance -= amount
        return True

    def get_balance(self):
        return self.balance


account = Account(1000)

account.deposit(500)
account.withdraw(200)

print(account.get_balance())

Output:

1300

Here:

  • Account is a class.
  • account is an object.
  • balance is an object attribute.
  • deposit(), withdraw(), and get_balance() are object methods.

Objects are responsible for managing their own state and provide operations to the outside through methods.

3. Basic Structure of Object-Oriented Programming

flowchart TB
    A["Account Class"] --> B["Attributes"]
    A --> C["Methods"]
    B --> D["Account Balance"]
    B --> E["Account Number"]
    C --> F["Deposit"]
    C --> G["Withdraw"]
    C --> H["Check Balance"]
    A --> I["Create Account Object"]
    I --> J["Object Has Independent State"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

4. Four Core Features of Object-Oriented Programming

Object-oriented programming usually revolves around encapsulation, inheritance, polymorphism, and abstraction.

4.1 Encapsulation

Encapsulation is the practice of organizing data and the methods that operate on that data together, and controlling external access through well-defined interfaces.

For example:

public class Account {
    private double balance;

    public Account(double balance) {
        this.balance = balance;
    }

    public void deposit(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("金额必须大于零");
        }

        balance += amount;
    }

    public double getBalance() {
        return balance;
    }
}

Here:

  • balance is declared with the private modifier.
  • External code cannot access this field directly.
  • Deposits are performed through the deposit() method.
  • The object can maintain business rules inside its methods.

The point of encapsulation is not simply to hide variables, but to protect an object's invariants.

For example, a bank account balance must not become an unreasonable value due to a single invalid operation.

4.2 Inheritance

Inheritance allows one class to extend the attributes and behavior of another class.

For example:

class Animal {
    public void eat() {
        System.out.println("动物进食");
    }
}

class Dog extends Animal {
    public void bark() {
        System.out.println("狗在叫");
    }
}

Dog inherits from Animal, so it can use the eat() method defined by the parent class while adding its own bark() method.

Inheritance can reuse code, but that does not mean all code reuse should use inheritance.

If two classes merely have the same functionality, that does not mean they necessarily have a reasonable inheritance relationship.

4.3 Polymorphism

Polymorphism allows objects of different types to exhibit different behavior through a unified interface.

For example:

interface Animal {
    void speak();
}

class Dog implements Animal {
    public void speak() {
        System.out.println("汪汪");
    }
}

class Cat implements Animal {
    public void speak() {
        System.out.println("喵喵");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal animal1 = new Dog();
        Animal animal2 = new Cat();

        animal1.speak();
        animal2.speak();
    }
}

Output:

汪汪
喵喵

Although both objects call speak() through the Animal interface, the actual execution results are different.

This reflects the core idea of polymorphism: a unified interface with different implementations.

4.4 Abstraction

Abstraction is the process of extracting the core characteristics of a thing and hiding unnecessary implementation details.

For example, when developers use a payment interface, they only need to focus on:

payment.pay(100);

They usually do not need to know how it is done internally:

  • Order validation.
  • Payment channel selection.
  • Signature generation.
  • Network requests.
  • Payment result handling.

Abstraction lets users focus on business capabilities rather than the specific implementation process.

5. Object-Oriented Collaboration Mechanisms

A complex system usually consists of multiple objects, which collaborate through method calls, message passing, or interfaces.

flowchart TB
    A["Order object"] --> B["Call payment interface"]
    B --> C["Payment object"]
    C --> D["Execute payment logic"]
    D --> E["Return payment result"]
    E --> A
    A --> F["Update order status"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

This design assigns different responsibilities to different objects, reducing the complexity that any single module has to bear.

6. Advantages of Object-Oriented Programming

  • Encapsulation: Organizes data and behavior together and controls how object state is modified.
  • Extensibility: System capabilities can be extended through interfaces, composition, and inheritance.
  • Modularity: Code is organized by business objects and responsibilities.
  • Maintainability: Sensible object boundaries can reduce coupling between modules.
  • Polymorphism: Allows different implementations to follow a unified interface.

7. Limitations of Object-Oriented Programming

High design complexity

For simple tasks, creating a large number of classes and objects may add unnecessary complexity.

Inheritance hierarchies tend to bloat

Complex inheritance hierarchies can create strong coupling between parent and child classes.

Object state management is complex

When mutable state is shared between objects, concurrency issues and state inconsistency can arise.

Over-engineering

If all logic is wrapped into classes, the code may instead end up redundant.

8. Applicable Scenarios

  • Enterprise business systems.
  • Domain models such as orders, users, and payments.
  • Large-scale applications.
  • Management of complex business rules.
  • Systems that need to be extended through interfaces.
  • Software architectures involving collaboration among multiple modules.

IV. Functional Programming

1. Core Idea

Functional programming treats functions as the core unit of computation, building programs through function composition and data transformation.

It emphasizes expressing computation as the composition of functions and minimizing shared mutable state and side effects.

Unlike traditional imperative programs, which modify variables extensively, functional programming focuses more on:

  • What the input data is.
  • Which transformations the data goes through.
  • What the output result is.
  • How different computations are composed.

For example:

def double(x):
    return x * 2


numbers = [1, 2, 3, 4, 5]

result = list(map(double, numbers))

print(result)

Output:

[2, 4, 6, 8, 10]

Here, map() applies the function to each element to produce a new data collection.

2. Core Characteristics of Functional Programming

2.1 Pure Functions

Pure functions are an important concept in functional programming.

A pure function generally satisfies two conditions:

  1. The same input always produces the same output.
  2. Execution has no observable external side effects.

For example:

def add(a, b):
    return a + b

Calling:

print(add(10, 20))
print(add(10, 20))

always yields the same result.

Such functions do not depend on external state, nor do they modify external data.

By contrast:

total = 0

def add(value):
    global total
    total += value
    return total

This function depends on the external variable total, so the same input may produce different outputs; therefore it is not a pure function.

Pure functions have the following advantages:

  • Easier to test.
  • Easier to reason about.
  • Easier to reuse.
  • Better suited to parallel computing.
  • Easier to cache and reuse results.

It should be noted that pure functions are an important practical goal in functional programming, but not every functional program must be completely free of side effects. Real-world applications still need to handle files, networks, databases, and user input.

2.2 Immutability

Immutability emphasizes that data is not modified directly after creation; instead, new data is generated through transformation.

For example:

numbers = [1, 2, 3]

new_numbers = numbers + [4]

print(numbers)
print(new_numbers)

Output:

[1, 2, 3]
[1, 2, 3, 4]

The original list remains unchanged, and the new list stores the transformation result.

Immutable data can reduce the problem of shared state being accidentally modified.

However, note that immutability in Python is not enforced by default. Objects such as lists and dictionaries can still be modified; developers need to implement this idea through design and constraints.

2.3 Higher-Order Function

A higher-order function is a function that satisfies any one of the following conditions:

  • Takes a function as an argument.
  • Returns a function as a result.

For example:

def apply(func, value):
    return func(value)


def square(x):
    return x * x


print(apply(square, 5))

Output:

25

Here, apply() takes another function as an argument, so it is a higher-order function.

Common higher-order functions in Python include:

  • map()
  • filter()
  • sorted()
  • reduce()

2.4 Function Composition

Function composition connects multiple functions so that the output of one function becomes the input of another.

Mathematical expression:

(f \circ g)(x) = f(g(x))

For example:

def double(x):
    return x * 2


def add_ten(x):
    return x + 10


def compose(f, g):
    return lambda x: f(g(x))


calculate = compose(add_ten, double)

print(calculate(5))

Output:

20

Execution process:

  • Input 5.
  • double(5) yields 10.
  • add_ten(10) yields 20.

Function composition can split complex calculations into multiple small functions with clear responsibilities.

2.5 Declarative Data Processing

Functional programming often expresses data processing through functions such as map(), filter(), and reduce().

For example:

numbers = [1, 2, 3, 4, 5, 6]

result = list(
    map(
        lambda x: x * 2,
        filter(lambda x: x % 2 == 0, numbers)
    )
)

print(result)

Output:

[4, 8, 12]

The logic:

  • Filter even numbers.
  • Multiply each even number by 2.
  • Generate a new result collection.

3. Data Processing Flow in Functional Programming

flowchart LR
    A["Raw data"] --> B["Filter (filter)"]
    B --> C["Transform (map)"]
    C --> D["Aggregate (reduce)"]
    D --> E["Final result"]

    style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

4. Advantages of Functional Programming

Reduce state complexity

Reducing shared mutable data can lower the difficulty of state management.

Easier to test

Pure functions depend only on their inputs, so testing does not require preparing a complex external environment.

Improve composability

Small functions can be combined to build complex calculations.

Favors concurrent processing

Reducing shared mutable state can alleviate some concurrency problems.

Expresses data transformation relationships

For data processing tasks such as filtering, mapping, and aggregation, the functional style is usually clearer.