Object Oriented Programming (OOP) vs Functional Programming

Learn the core ideas behind Object‑Oriented Programming and Functional Programming, compare their pros and cons, and see easy Python examples to choose the right paradigm.

Programming Coding Object Oriented Programming Functional Programming

Why Programming Paradigms Matter

Programming paradigms are like philosophies that shape how you solve problems. Knowing more than one gives you extra tools, much like learning both a brush and a spray can if you are a painter. Two of the most influential are Object‑Oriented Programming (OOP) and Functional Programming (FP).

Quick Definitions

ParadigmOne‑Sentence Summary
OOPModel the world as objects that hold state (data) and behavior (methods).
FPBuild programs by composing stateless functions that transform data.

Core Concepts at a Glance

ConceptOOP TermFP Term
Building BlockObject (instance of a class)Pure Function
State HandlingMutable fields inside objectsImmutable data
BehaviourMethodsFunction composition
Code Re‑useInheritance / InterfacesHigher‑order functions / Closures
Flow ControlImperative (step by step)Declarative (what, not how)

Object‑Oriented Programming in Depth

Fundamental Ideas

Where OOP Shines

Simple Python Example

Code Language
 1class BankAccount:
 2    def __init__(self, owner, balance = 0.0):
 3        self.owner = owner
 4        self._balance = balance  # underscore hints “private”
 5
 6    def deposit(self, amount):
 7        self._balance += amount
 8
 9    def withdraw(self, amount):
10        if amount > self._balance:
11            raise ValueError("Insufficient funds")
12        self._balance -= amount
13
14    def __str__(self):
15        return f"{self.owner}'s balance is: ${self._balance:,.2f}"
16
17# Usage
18acc = BankAccount("Alex", 100)
19acc.deposit(50)
20print(acc)                # Alex's balance: $150.00

Explanation of the above code

  1. Defines a BankAccount class
  2. __init__(…)** — initiates a new account**
  3. deposit(…)** — adds money**
  4. withdraw(…)** — removes money safely**
  5. __str__(…)** — neat print‑out**
  6. Usage example

In short, this class models a simple bank account: you can create it with an owner and opening balance, deposit money, withdraw money with built‑in safety checks, and print the current balance in a human readable format.


Functional Programming in Depth

Fundamental Ideas

Where Functional Shines

Simple Python Example

Code Language
1# Pure function → never changes anything outside itself
2def add_tax(price, tax_rate=0.1):
3    """Return price including a 10 % sales tax by default."""
4    return price * (1 + tax_rate)

Side‑by‑Side Example: Greeting Users

OOP Style

Code Language
 1# 1. Define class Greeter
 2class Greeter:
 3    def __init__(self, greeting):
 4        self.greeting = greeting
 5
 6    def greet(self, name):
 7        return f"{self.greeting}, {name}!"
 8
 9# 2. Create an instance of Greeter class (initialised with a greeting message)
10hello = Greeter("Hello")
11
12# 3. Use it
13print(hello.greet("Ved"))

Functional Style

Code Language
1# 1. make_greeter returns a NEW function
2def greet(greeting, name):
3    return f"{greeting}, {name}!"
4
5# 2. Use it
6print(greet("Hello", "Ved"))

Both snippets output “Hello, Ved!” but reflect different mind‑sets: OOP bundles data and behavior; FP builds reusable, stateless functions.


Strengths and Trade‑Offs

AspectOOPFunctional
Learning CurveFamiliar if you think in “things.”Might feel abstract at first.
State ManagementBuilt‑in via mutable objects.Encourages immutability and safer concurrency.
TestingRequires mocks for object state.Simple: pure functions are easy to test.
PerformanceMay allocate more memory per object.Often lighter but can incur overhead from frequent allocations.
Code ReuseInheritance and interfaces.Small composable functions reused through composition.

Languages to Practice Each Paradigm

ParadigmLanguages Well‑Suited
Object‑OrientedJava, C++, C#, Python, Ruby, Swift, Kotlin
FunctionalHaskell, Elixir, Clojure, F#, OCaml, Erlang
Multi‑ParadigmJavaScript (with Ramda), Scala, Rust, Kotlin, Python, TypeScript

Tip: Python supports both styles, making it a gentle playground to explore and mix paradigms.


Practical Exercise: Build a To‑Do List Both Ways

  1. OOP Version. Create a Task class with properties like title, priority, and a TodoList class with methods add_task, remove_task, and mark_complete.
  2. Functional Version. Represent each task as an immutable dictionary and write pure functions such as add_task(list, task) and complete_task(list, task_id) that return new lists.

Compare how each feels, especially when you add concurrency or unit tests.


Best Learning Resources


Conclusion

Both Object‑Oriented and Functional Programming give you structured ways to break down complex problems. OOP mirrors real‑world objects, while FP treats computation like a pipeline of data transformations. Try re‑implementing a small project in both styles, notice the differences, and choose the paradigm—or blend—that helps you write clearer, safer, and more maintainable code.