Skip to main content

Functional vs Class-Based Programming: Simple Guide for Backend Interviews

Overview​

This guide explains functional programming and class-based (object-oriented) programming in simple terms. No buzzwords. Just clear explanations with code you can run.

Target: Backend engineers interviewing for Python/SaaS roles (2026)


Table of Contents​

  1. Quick Answer: What's the Difference?
  2. Functional Programming Explained Simply
  3. Class-Based Programming Explained Simply
  4. Interview Questions & Answers
  5. Common Mistakes in Interviews
  6. Advanced Interview Topics
  7. Advanced Comparison: Python-Specific Considerations
  8. Summary Cheat Sheet

Quick Answer: What's the Difference?​

Functional Programming (FP):

  • Functions only. No objects.
  • Data never changes after creation (immutable).
  • Same input always gives same output (pure functions).
  • No hidden state. Everything is explicit.

Class-Based Programming (OOP):

  • Code lives in classes and objects.
  • Data can change (mutable).
  • Objects keep their own state.
  • Methods can modify internal data.

Simple analogy:

  • FP: Like a math formula. f(x) = x². Input 3, always get 9.
  • OOP: Like a robot. The robot remembers things (state) and can change its own memory.

Functional Programming Explained Simply​

Core Idea​

Write functions that:

  1. Take input
  2. Do one calculation
  3. Return output
  4. Never change anything else

That's it.

Example: Simple Math Functions​

# ✅ GOOD: Pure function - always same result
def add_tax(price, tax_rate):
return price * (1 + tax_rate)

print(add_tax(100, 0.1)) # 110.0
print(add_tax(100, 0.1)) # 110.0 (same every time)
# ❌ BAD: Impure function - result depends on hidden state
TAX_RATE = 0.1 # Global variable can change

def add_tax_bad(price):
return price * (1 + TAX_RATE) # Depends on global

Why pure functions matter:

  • Easy to test (no setup needed)
  • No surprises (no hidden dependencies)
  • Safe to run anywhere, anytime

Immutability: Don't Change Data, Create New Data​

# ❌ BAD: Modifying original data
users = [
{'id': 1, 'name': 'Alice'},
{'id': 2, 'name': 'Bob'}
]

def rename_user_bad(user_list, user_id, new_name):
for user in user_list:
if user['id'] == user_id:
user['name'] = new_name # Changes original!
return user_list

result = rename_user_bad(users, 1, 'Alice Updated')
print(users[0]['name']) # 'Alice Updated' - original changed!
# ✅ GOOD: Create new data, keep original unchanged
def rename_user(users, user_id, new_name):
return [
{**user, 'name': new_name} if user['id'] == user_id else user
for user in users
]

result = rename_user(users, 1, 'Alice Updated')
print(users[0]['name']) # 'Alice' - original safe
print(result[0]['name']) # 'Alice Updated' - new data

Benefits:

  • No accidental changes
  • Easy to track what changed
  • Safer in multi-threaded code

Functions Are Just Values​

# Functions can be assigned to variables
def greet(name):
return f"Hello, {name}!"

say_hello = greet # Assign function to variable
print(say_hello("Alice")) # Works

# Functions can be passed as arguments
def process_data(data, transformer):
return [transformer(item) for item in data]

numbers = [1, 2, 3]
doubled = process_data(numbers, lambda x: x * 2)
print(doubled) # [2, 4, 6]

Built-in Tools: map, filter, reduce​

These are just shortcuts for common loops:

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

# map: apply function to each item
squared = list(map(lambda x: x**2, numbers))
# Same as: [x**2 for x in numbers]

# filter: keep items that match condition
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Same as: [x for x in numbers if x % 2 == 0]

# reduce: combine all items into one
from functools import reduce
total = reduce(lambda a, b: a + b, numbers, 0)
# Same as: sum(numbers)

Bottom line: FP is about writing small, predictable functions and combining them.


Class-Based Programming Explained Simply​

Core Idea​

Group related data and functions together into objects.

  • Class = blueprint (like "Car" design)
  • Object = actual thing made from blueprint (like "my Car")
  • Attributes = data the object stores
  • Methods = actions the object can do

Example: Simple Class​

# Blueprint for a tenant
class Tenant:
def __init__(self, tenant_id, name):
self.tenant_id = tenant_id # Data stored in object
self.name = name
self.users = [] # Each tenant keeps its own user list

def add_user(self, user):
"""Action the tenant can do"""
self.users.append(user)

def user_count(self):
return len(self.users)

# Create actual tenant objects
acme = Tenant("acme-123", "Acme Corp")
acme.add_user({"name": "Alice"})
acme.add_user({"name": "Bob"})

beta = Tenant("beta-456", "Beta Inc")

print(acme.user_count()) # 2 - acme's own users
print(beta.user_count()) # 0 - beta's own users

Key point: Each object keeps its own separate data.

Encapsulation: Hiding Internal Details​

class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private - outside code can't touch

def deposit(self, amount):
if amount > 0:
self.__balance += amount

def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
return amount
return 0

def get_balance(self):
return self.__balance

# Safe: Can't set balance directly
account = BankAccount(1000)
account.deposit(100)
print(account.get_balance()) # 1100

# This fails (can't access __balance):
# account.__balance = 1000000 # AttributeError

Why encapsulate?

  • Prevent invalid states (can't set negative balance)
  • Change internal code without breaking external code
  • Control access (read-only vs read-write)

Inheritance: Sharing Code Between Similar Things​

# Base class
class User:
def __init__(self, user_id, email):
self.user_id = user_id
self.email = email

def send_email(self, message):
return f"Sending to {self.email}: {message}"

# Child class inherits from User
class TenantUser(User):
def __init__(self, user_id, email, tenant_id):
super().__init__(user_id, email)
self.tenant_id = tenant_id
self.role = "member"

def can_access_tenant(self, tenant_id):
return self.tenant_id == tenant_id

# Another child class
class AdminUser(User):
def __init__(self, user_id, email, tenant_id):
super().__init__(user_id, email)
self.tenant_id = tenant_id
self.role = "admin"

def can_access_tenant(self, tenant_id):
return True # Admins can access any tenant

# Using them
user = TenantUser("u1", "user@acme.com", "acme-123")
admin = AdminUser("a1", "admin@acme.com", "acme-123")

print(user.can_access_tenant("acme-123")) # True
print(user.can_access_tenant("other-456")) # False
print(admin.can_access_tenant("other-456")) # True

Benefits of inheritance:

  • Reuse code (don't repeat yourself)
  • Common interface (all Users have send_email)
  • Easy to extend with new types

Polymorphism: Same Interface, Different Behavior​

from abc import ABC, abstractmethod

# Abstract base class - defines what must be implemented
class PaymentProcessor(ABC):
@abstractmethod
def charge(self, amount):
pass

# Different implementations
class StripeProcessor(PaymentProcessor):
def charge(self, amount):
return f"Stripe charged ${amount}"

class PayPalProcessor(PaymentProcessor):
def charge(self, amount):
return f"PayPal charged ${amount}"

# Function works with ANY processor
def process_payment(processor: PaymentProcessor, amount):
return processor.charge(amount)

# Same function, different behavior
stripe = StripeProcessor()
paypal = PayPalProcessor()

print(process_payment(stripe, 100)) # Stripe charged $100
print(process_payment(paypal, 100)) # PayPal charged $100

Why it matters:

  • Write code once, works with many implementations
  • Easy to switch implementations (e.g., change payment provider)
  • Testing is easier (use fake processor)

Interview Questions & Answers​

Q1: What's the simplest way to explain functional programming?​

Simple answer: Functional programming means writing functions that:

  • Always return the same result for the same inputs
  • Don't change anything outside the function
  • Don't use mutable data (data that changes)

Example:

# Functional: predictible, no side effects
def calculate_total(items):
return sum(item['price'] for item in items)

# Not functional: depends on outside state, has side effect
total = 0
def calculate_total_bad(items):
global total
total = sum(item['price'] for item in items) # Changes global!
return total

🔍 What interviewers test: Do you understand pure functions and why they're safer?

❌ Common mistakes:

  • Saying FP means "no classes" (that's not the point)
  • Confusing immutability with constants
  • Not being able to give a concrete example

Q2: What's the difference between a class and a function?​

Simple answer:

  • Function: A reusable piece of code that does one job. Input → output.
  • Class: A blueprint for creating objects that hold both data and functions.

Code comparison:

# Function approach - data separate, functions separate
def create_user(name, email):
return {"name": name, "email": email}

def send_welcome(user):
print(f"Sending email to {user['email']}")

user = create_user("Alice", "alice@example.com")
send_welcome(user)
# Class approach - data and functions together
class User:
def __init__(self, name, email):
self.name = name
self.email = email

def send_welcome(self):
print(f"Sending email to {self.email}")

user = User("Alice", "alice@example.com")
user.send_welcome() # Data and behavior together

🔍 What interviewers test: Do you understand when to group data with behavior?

❌ Common mistakes:

  • Saying classes are "better" or functions are "better" (context matters)
  • Not understanding when to use each
  • Using classes for everything (over-engineering)

Q3: When should I use a function vs a class?​

Use functions when:

  1. Doing one calculation (e.g., calculate_tax(amount, rate))
  2. Transforming data (e.g., filter_active_users(users))
  3. No state to remember (stateless operations)
  4. Easy to test in isolation
  5. Will run in parallel (no shared data)

Use classes when:

  1. Need to remember state (e.g., database connection pool)
  2. Grouping related data and behavior (e.g., User with name, email, send_email())
  3. Multiple similar objects that share code (e.g., Tenant, Project, Task)
  4. Need polymorphism (different behaviors for same interface)
  5. Complex business logic with many related functions

Real backend example:

# Function approach: Data processing pipeline
def process_tenant_csv(csv_data):
rows = parse_csv(csv_data)
filtered = [r for r in rows if r['active']]
return sorted(filtered, key=lambda r: r['revenue'])

# Class approach: Application state
class TenantManager:
def __init__(self):
self.tenants = {} # State we need to remember
self.cache = {}

def add_tenant(self, tenant):
self.tenants[tenant.id] = tenant

def find_tenant(self, tenant_id):
# Check cache first, then database
if tenant_id in self.cache:
return self.cache[tenant_id]
tenant = db.query(tenant_id)
self.cache[tenant_id] = tenant
return tenant

🔍 What interviewers test: Practical decision-making, not dogma.

❌ Common mistakes:

  • "Always use classes" (FP is often simpler)
  • "Always use functions" (state needs to live somewhere)
  • Not being able to justify the choice

Q4: What is immutability and why does it matter in multi-tenant SaaS?​

Simple answer: Immutability means once you create data, you never change it. To "update", you create a new copy with the changes.

Example:

# Immutable approach - safer for multi-tenant
def update_tenant_name(tenants, tenant_id, new_name):
# Create new list, don't modify original
return [
{**t, 'name': new_name} if t['id'] == tenant_id else t
for t in tenants
]

all_tenants = [{'id': 't1', 'name': 'Old'}]
updated = update_tenant_name(all_tenants, 't1', 'New')

print(all_tenants[0]['name']) # 'Old' - original unchanged
print(updated[0]['name']) # 'New' - new data

Why it matters:

  1. No race conditions: Two users can "update" at same time without conflicts

    # Alice and Bob both update tenant name
    # Immutable: both get fresh copy, both create new version
    # Mutable: last write wins, one person's changes lost
  2. Easier debugging: Old data still exists. You can see what changed.

  3. Safe caching: Cached data can't be modified by accident.

  4. Thread-safe: No locks needed when data never changes.

When immutability is painful:

  • Very large datasets (copying expensive)
  • Real-time systems (performance critical)
  • Simple CRUD apps (overkill)

🔍 What interviewers test: Understanding of data safety, concurrency, tradeoffs.

❌ Common mistakes:

  • "Immutability is always better" (not true, has costs)
  • Not understanding when to break immutability
  • Can't explain concrete benefits for multi-tenant systems

Q5: What's the difference between composition and inheritance?​

Simple answer:

  • Inheritance: "Is-a" relationship. Child gets parent's code.
  • Composition: "Has-a" relationship. Object contains other objects.

Visual:

Inheritance: AdminUser IS-A User (inherits everything)
Composition: User HAS-A EmailService (contains it)

Code:

# ❌ INHERITANCE - fragile, tight coupling
class EmailUser(User): # "is-a" User
pass

# Changes to User might break EmailUser
# ✅ COMPOSITION - flexible, loose coupling
class User:
def __init__(self, email_service):
self.email_service = email_service # "has-a" service

def send_welcome(self):
self.email_service.send(self.email, "Welcome!")

# Can swap email services easily
user = User(SendGridService())
user = User(MailgunService())

Rule: Prefer composition over inheritance.

🔍 What interviewers test: Understanding of code coupling and flexibility.

❌ Common mistakes:

  • Deep inheritance hierarchies (God classes)
  • Using inheritance to share code (use composition instead)
  • Not knowing when each is appropriate

Q6: What is a "pure function" and why should I care?​

Simple answer: A pure function:

  1. Same inputs → same outputs (every time)
  2. No side effects (doesn't change anything outside itself)

Example:

# Pure function
def calculate_discount(price, discount_percent):
return price * (1 - discount_percent / 100)

# Not pure - depends on outside state
DISCOUNT_RATE = 0.1
def calculate_discount_bad(price):
return price * (1 - DISCOUNT_RATE) # Changes if DISCOUNT_RATE changes

# Not pure - has side effect
def calculate_discount_worse(price):
print(f"Calculating discount for {price}") # Side effect!
return price * 0.9

Why you should care:

  1. Easy to test: No setup, no mocking

    assert calculate_discount(100, 10) == 90
    assert calculate_discount(100, 10) == 90 # Same every time
  2. Safe to refactor: No hidden dependencies

  3. Parallelizable: Can run on multiple CPUs safely

  4. Predictable: No surprises in production

In backend interviews: They'll ask you to write pure functions for business logic.

🔍 What interviewers test: Writing testable, maintainable code.

❌ Common mistakes:

  • Functions that read from database (side effect)
  • Functions that modify global variables
  • Functions that depend on "current user" from context
  • Not understanding why purity helps

Q7: What are the performance differences?​

Simple comparison:

OperationFunctional (Immutable)Class-Based (Mutable)
Create new dataSlower (copies data)Fast (modify in place)
Memory usageHigher (new objects)Lower (reuse same object)
Thread safetyFree (no locks)Needs locks for shared data
CPU cachePoorer (new objects)Better (same memory)

Numbers (approximate):

  • Immutable update: ~2-3x slower, ~2-3x memory
  • Mutable update: Faster, less memory

When it matters:

  • High-frequency trading: Use mutable (every nanosecond counts)
  • Data pipelines: Use immutable (correctness > speed)
  • Web backend (most cases): Tradeoff doesn't matter much. Choose based on clarity.

Real backend example:

# Immutable - safer but slightly slower
def update_tenant(tenant, updates):
return {**tenant, **updates} # Creates new dict

# Mutable - faster but risky
def update_tenant_mutable(tenant, updates):
tenant.update(updates) # Changes original

Bottom line: For most web backends, clarity > micro-optimization. Pick based on team understanding, not raw speed.

🔍 What interviewers test: Understanding tradeoffs, not just "which is faster".

❌ Common mistakes:

  • "FP is always slower" (sometimes it's faster due to no locks)
  • "Performance is the only factor" (maintainability matters more)
  • Not knowing how to measure/benchmark

Q8: Which approach is better for testing?​

Simple answer: Pure functions are easiest to test. Classes are harder but manageable with good design.

Comparison:

# ✅ EASY TO TEST - Pure function
def calculate_bill(tenant, usage):
rate = 0.1 if tenant['plan'] == 'pro' else 0.05
return usage * rate

# Test:
def test_calculate_bill():
assert calculate_bill({'plan': 'pro'}, 100) == 10
assert calculate_bill({'plan': 'free'}, 100) == 5
# No setup. No mocks. Just input → output.
# ⚠️ HARDER TO TEST - Class with dependencies
class BillingService:
def __init__(self, db, payment_processor):
self.db = db
self.payment = payment_processor

def bill_tenant(self, tenant_id):
tenant = self.db.get(tenant_id) # Need mock DB
usage = self.db.get_usage(tenant_id) # Need mock DB
amount = self.calculate(tenant, usage) # Actual logic
return self.payment.charge(amount) # Need mock payment

# Test requires mocking database and payment:
def test_bill_tenant():
db = MockDB()
payment = MockPayment()
service = BillingService(db, payment)
# ... complex setup

Testing strategy by paradigm:

Functional approach:

# Most logic in pure functions
def calculate_total(items): ...
def apply_discount(total, coupon): ...
def format_invoice(total): ...

# Thin wrapper (minimal code to test)
class InvoiceService:
def generate(self, items, coupon):
total = calculate_total(items) # Test separately
discounted = apply_discount(total, coupon) # Test separately
return format_invoice(discounted) # Test separately

Class-based approach (well-designed):

class InvoiceService:
def __init__(self, calculator, discount_applier, formatter):
self.calculator = calculator # Injected dependency
self.discount_applier = discount_applier
self.formatter = formatter

def generate(self, items, coupon):
total = self.calculator.calculate(items)
discounted = self.discount_applier.apply(total, coupon)
return self.formatter.format(discounted)

# Test: inject fake implementations
def test_generate():
service = InvoiceService(
calculator=FixedCalculator(100), # Returns 100 always
discount_applier=FixedDiscount(0.9), # 10% off
formatter=SimpleFormatter()
)
assert service.generate([], None) == "90.00"

🔍 What interviewers test: Can you write testable code? Do you understand test doubles?

❌ Common mistakes:

  • Writing monolithic functions that do everything (hard to test)
  • Creating classes that can't be isolated (tightly coupled)
  • Not using dependency injection
  • Thinking "I'll just test the whole thing together" (integration tests are slow)

Q9: What about concurrency and multi-threading?​

Simple answer: Functional code (immutable data) is naturally thread-safe. Class-based code (mutable state) needs locks.

Example:

# ✅ THREAD-SAFE: Pure function - no shared state
def process_user(user_id):
# Every call independent
user = get_user(user_id) # Read from DB
return transform(user)

# Can run 100 threads simultaneously, no conflicts
# ⚠️ NOT THREAD-SAFE: Shared mutable state
class Counter:
def __init__(self):
self.value = 0

def increment(self):
self.value += 1 # Not atomic! Race condition!

# Two threads calling increment() at same time:
# Thread A reads: value = 0
# Thread B reads: value = 0
# Thread A writes: value = 1
# Thread B writes: value = 1 (lost increment!)

Fixing mutable class for threads:

import threading

class SafeCounter:
def __init__(self):
self.value = 0
self.lock = threading.Lock()

def increment(self):
with self.lock: # Only one thread at a time
self.value += 1

# Now safe, but slower due to lock contention

Backend reality:

  • Web servers (Gunicorn, Uvicorn) already use multiple processes
  • Within one process, prefer async/await over threads
  • Immutable data structures avoid most concurrency bugs

🔍 What interviewers test: Do you understand race conditions? Can you write thread-safe code?

❌ Common mistakes:

  • "Python's GIL makes threads safe" (GIL prevents CPU parallel but not I/O race conditions)
  • Not understanding when locks are needed
  • Overusing locks (hurts performance)

Q10: How do I choose for a multi-tenant SaaS backend?​

Decision flow:

Need to store and modify tenant state? → Use classes
Tenant with: database connections, cache, settings, users

Doing calculations or transformations? → Use functions
Calculate: bill, usage, metrics, reports

Both? → Use both (hybrid)

Pattern:

# Classes for what needs to persist/change
class Tenant:
def __init__(self, tenant_id, name):
self.tenant_id = tenant_id
self.name = name
self._users = []
self._settings = {}

def add_user(self, user):
self._users.append(user) # State changes

def update_setting(self, key, value):
self._settings[key] = value # State changes

# Functions for business logic
def calculate_tenant_usage(tenant_id, start_date, end_date):
"""Pure function - given inputs, compute output"""
usage = db.query(tenant_id, start_date, end_date)
return sum(u['amount'] for u in usage)

def format_usage_report(usage_data):
"""Pure function - format without side effects"""
return f"Total usage: {usage_data} units"

Why hybrid works best for SaaS:

  • Classes model domain entities (Tenant, User, Project)
  • Functions implement business rules (no hidden state)
  • Easy to test logic separately from state
  • Clear separation: "Where does data live?" vs "How do we compute?"

Common Mistakes in Interviews​

Mistake 1: "Functional is always better"​

Reality: No. FP is good for specific cases. OOP is good for others. Understand tradeoffs.

Good answer:

"I use FP for data transformations and calculations where purity helps testing. I use OOP for domain models where encapsulating state with behavior makes sense. Most production codebases use both."

Mistake 2: "Classes are just functions with state"​

Reality: Not exactly. Classes provide:

  • Encapsulation (hide implementation)
  • Polymorphism (swap implementations)
  • Inheritance (share code, though often misused)

Good answer:

"Classes group related data and operations, enforce invariants through encapsulation, and support polymorphism. A function + dict doesn't give you that."

Mistake 3: "I never use inheritance"​

Reality: Inheritance is overused but not evil. Know when it's appropriate.

Good answer:

"I prefer composition but use inheritance for clear 'is-a' relationships with shared base behavior. For example, different payment processors all implement a common interface. But I avoid deep inheritance chains."

Mistake 4: Not giving concrete examples​

Bad answer:

"FP is about immutability and pure functions..."

Good answer:

"In my last project, I used pure functions for tax calculation so I could unit test all edge cases without database fixtures. For tenant management, I used classes to encapsulate state and used dependency injection to swap implementations for testing."


Advanced Interview Topics​

Q11: How do error handling patterns differ between FP and OOP?​

Simple answer: Functional programming uses explicit error returns (no exceptions). OOP uses exceptions for exceptional cases.

Why it matters: Backend interviews test error handling design.

FP approach - errors as data:

from typing import Optional, Tuple

# Function returns (success, result) tuple
def divide(a: float, b: float) -> Tuple[bool, Optional[float]]:
if b == 0:
return (False, None) # Error as data
return (True, a / b)

success, result = divide(10, 2)
if success:
print(f"Result: {result}")
else:
print("Division by zero")

# Or use Result monad pattern (FP style)
class Result:
def __init__(self, is_success, value=None, error=None):
self.is_success = is_success
self.value = value
self.error = error

@staticmethod
def success(value):
return Result(True, value=value)

@staticmethod
def failure(error):
return Result(False, error=error)

def safe_divide(a: float, b: float) -> Result:
if b == 0:
return Result.failure("Division by zero")
return Result.success(a / b)

result = safe_divide(10, 0)
if result.is_success:
print(result.value)
else:
print(f"Error: {result.error}")

OOP approach - exceptions:

def divide(a: float, b: float) -> float:
if b == 0:
raise ValueError("Cannot divide by zero") # Throw exception
return a / b

try:
result = divide(10, 0)
except ValueError as e:
print(f"Error: {e}")

Comparison:

AspectFunctionalOOP
Error typeReturn value (data)Exception (control flow)
Forced handling✅ Must check return value⚠️ Can forget try/except
CompositionEasy to chainHarder (try/except blocks)
Type safetyExplicit in signatureImplicit (can raise anything)
PerformanceFaster (no stack unwinding)Slower (exception overhead)

FP chaining example:

def process_file(filename) -> Result:
return (
read_file(filename) # Returns Result
.then(parse_json) # Chains if success
.then(validate_schema) # Chains if success
.then(save_to_db) # Chains if success
)
# Each step returns Result, stops on first failure

Python reality: Python uses exceptions (OOP style). FP-style error handling is rare in Python codebases.

When to use which:

  • Expected errors (validation, not found): Return values (FP style)
  • Unexpected errors (database down, network failure): Exceptions (OOP style)
# GOOD: Mix both appropriately
def get_user(user_id: str) -> Optional[User]:
"""Expected: user may not exist. Return None."""
user = db.find(user_id)
return user # None if not found (no exception)

def process_payment(amount: float) -> Receipt:
"""Unexpected: payment processor failure. Raise exception."""
if not payment_gateway.is_available():
raise PaymentUnavailableError("Gateway down")
return payment_gateway.charge(amount)

🔍 What interviewers test: Do you understand error handling trade-offs? Can you design APIs that are safe to use?

❌ Common mistakes:

  • Using exceptions for control flow (e.g., try/except for "not found")
  • Not returning errors in FP style (just crash)
  • Mixing both randomly without strategy
  • Not documenting what errors a function can return/raise

Q12: How does async/await affect the choice between FP and OOP?​

Simple answer: Both paradigms work with async. FP tends to be cleaner for async pipelines. OOP needs careful design to avoid blocking.

Async with functions:

import asyncio

# Pure-ish async functions
async def fetch_user(user_id: int) -> dict:
"""Async function - still pure if no side effects"""
return await db.get_user(user_id)

async def calculate_bill(user_id: int) -> float:
user = await fetch_user(user_id) # Await other functions
return user['balance'] * 0.1

# Async pipeline
async def process_tenants(tenant_ids: list):
tasks = [calculate_bill(tid) for tid in tenant_ids]
bills = await asyncio.gather(*tasks) # Run concurrently
return sum(bills)

# Run
asyncio.run(process_tenants([1, 2, 3]))

Async with classes:

class AsyncTenantService:
def __init__(self, db_pool):
self.db_pool = db_pool

async def get_tenant(self, tenant_id: str) -> dict:
"""Async method - careful: self modifies state?"""
async with self.db_pool.acquire() as conn:
return await conn.fetchrow("SELECT * FROM tenants WHERE id = $1", tenant_id)

async def update_usage(self, tenant_id: str, units: int):
"""Async method with state modification"""
async with self.db_pool.acquire() as conn:
await conn.execute(
"UPDATE tenants SET usage = usage + $1 WHERE id = $2",
units, tenant_id
)

# Usage
service = AsyncTenantService(pool)
await service.update_usage("tenant-123", 10)

Key considerations:

  1. Async functions are naturally composable (FP style):
# Clean composition
result = await (
fetch_user(1)
| validate_email
| calculate_score
)
  1. OOP with async needs dependency injection:
class BillingService:
def __init__(self, user_repo, payment_processor):
self.user_repo = user_repo # Async dependency
self.payment = payment_processor # Async dependency

async def bill_user(self, user_id: str):
user = await self.user_repo.get(user_id) # Await dependency
amount = self.calculate(user) # Sync (pure function)
return await self.payment.charge(amount) # Await dependency
  1. Avoid mixing sync I/O in async code:
# ❌ BAD: Blocking call in async function
async def get_data():
data = requests.get("https://api.example.com") # BLOCKS event loop!
return data

# ✅ GOOD: Use async HTTP client
async def get_data():
async with aiohttp.ClientSession() as session:
async with session.get("https://api.example.com") as resp:
return await resp.json()

Backend interview tip: When they ask "design a high-throughput API", you should mention:

  • Use async functions for I/O-bound operations
  • Keep business logic in pure functions (easy to test)
  • Use classes for stateful services (connection pools, caches)
  • Never block the event loop

🔍 What interviewers test: Understanding of async/await, event loop, avoiding blocking calls.

❌ Common mistakes:

  • Using time.sleep() in async code (blocks everything)
  • Forgetting to await async functions (returns coroutine, not result)
  • Mixing sync database drivers with async code
  • Not understanding when async actually helps (CPU-bound vs I/O-bound)

Q13: How do decorators work in both paradigms?​

Simple answer: Decorators are functions that wrap other functions or classes. They're a functional pattern that works great with both.

Decorator as function wrapper:

# Decorator = function that takes a function and returns a new function
def log_time(func):
"""Decorator: measures execution time"""
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.2f}s")
return result
return wrapper

@log_time
def process_data(items):
time.sleep(1)
return len(items)

# Same as: process_data = log_time(process_data)
result = process_data([1, 2, 3]) # Prints "process_data took 1.00s"

Decorators with classes:

# Decorator on class methods
class TenantService:
@staticmethod
def validate_tenant_id(tenant_id: str) -> bool:
"""Static method decorator"""
return bool(tenant_id)

@classmethod
def from_config(cls, config: dict):
"""Class method - creates instance"""
return cls(config['tenant_id'], config['name'])

@property
def tenant_count(self):
"""Property decorator - acts like attribute"""
return len(self._tenants)

# Class decorators (wrap entire class)
def singleton(cls):
"""Class decorator: ensures only one instance"""
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance

@singleton
class DatabaseConnection:
def __init__(self, url):
self.url = url

# Now DatabaseConnection() always returns same instance

FP-style decorator composition:

from functools import wraps

def log(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper

def validate_inputs(func):
@wraps(func)
def wrapper(*args, **kwargs):
# Validate before calling
for arg in args:
if arg is None:
raise ValueError("None not allowed")
return func(*args, **kwargs)
return wrapper

# Compose multiple decorators (FP composition!)
@validate_inputs
@log
def process_order(order_id: str, amount: float):
return f"Processed {order_id}: ${amount}"

# Stack order: @validate_inputs wraps @log wraps process_order
# Equivalent: process_order = validate_inputs(log(process_order))

OOP approach: decorator as mixin/class:

class Loggable:
"""Mixin class adds logging to any class"""
def log(self, message):
print(f"[{self.__class__.__name__}] {message}")

class TenantService(Loggable):
def create_tenant(self, name):
self.log(f"Creating tenant: {name}") # From Loggable mixin
# ... create logic

Interview answer:

"Decorators are a functional pattern (higher-order functions) that work equally well with functions and classes. I use them for cross-cutting concerns: logging, validation, caching, authentication. In OOP, I might use inheritance (mixin) instead, but decorators are more flexible and composable."

🔍 What interviewers test: Understanding of higher-order functions, composition, AOP (aspect-oriented programming) concepts.

❌ Common mistakes:

  • Not using @wraps (loses function metadata)
  • Decorator order confusion (top-down application)
  • Creating decorators with side effects
  • Not understanding that decorators run at import/definition time, not call time

Q14: Type hinting differences between FP and OOP​

Simple answer: FP uses type hints for function signatures (input → output). OOP uses type hints for class structure.

FP type hints:

from typing import Callable, List, Dict, Optional

# Functions as types
ProcessFunction = Callable[[int, str], bool]

def process_data(
data: List[dict],
transformer: Callable[[dict], bool],
filter_func: Optional[Callable[[dict], bool]] = None
) -> List[dict]:
"""Clear: takes list, returns list, uses function parameters"""
result = []
for item in data:
if transformer(item):
if filter_func is None or filter_func(item):
result.append(item)
return result

# Function composition types
Pipeline = Callable[[int], int]

def compose(f: Pipeline, g: Pipeline) -> Pipeline:
"""Compose two functions: f(g(x))"""
return lambda x: f(g(x))

OOP type hints:

from dataclasses import dataclass
from typing import Optional

@dataclass
class Tenant:
"""Type hints describe data structure"""
tenant_id: str
name: str
plan: str = "free"
users: list[str] = None

def __post_init__(self):
if self.users is None:
self.users = []

class TenantService:
def __init__(self, repository: 'TenantRepository'):
self.repo = repository

def get_tenant(self, tenant_id: str) -> Optional[Tenant]:
"""Return Tenant or None"""
return self.repo.find(tenant_id)

Key differences:

AspectFP Type HintsOOP Type Hints
FocusFunction signaturesClass attributes/methods
ExpressivenessHigher-order functionsInheritance hierarchies
ReuseFunction compositionClass inheritance
ClarityInput → output flowObject relationships

Protocols (structural typing) - FP-friendly:

from typing import Protocol

# Define behavior without inheritance
class Comparable(Protocol):
def __lt__(self, other: 'Comparable') -> bool: ...
def __eq__(self, other: 'Comparable') -> bool: ...

# Any class with < and == works
def sort_items(items: list[Comparable]):
return sorted(items)

# Both work without inheriting from Comparable
class User:
def __init__(self, name):
self.name = name
def __lt__(self, other):
return self.name < other.name

sort_items([User("Alice"), User("Bob")]) # ✅ OK

OOP with generics:

from typing import Generic, TypeVar

T = TypeVar('T') # Generic type

class Repository(Generic[T]):
"""Generic repository - works with any type"""
def __init__(self):
self._items: list[T] = []

def add(self, item: T):
self._items.append(item)

def get_all(self) -> list[T]:
return self._items

# Usage with type safety
user_repo = Repository[User]()
user_repo.add(User("Alice")) # ✅ Type checked
# user_repo.add("string") # ❌ Type error

Backend interview tip:

"I use type hints everywhere. For FP code, I type function signatures clearly. For OOP, I use dataclasses and protocols. Pydantic (FastAPI) combines both: classes with validation."

🔍 What interviewers test: Type safety knowledge, modern Python (3.9+), production code quality.

❌ Common mistakes:

  • No type hints at all (unprofessional in 2026)
  • Any everywhere (defeats the purpose)
  • Not using Optional, Union, Protocol appropriately
  • Type hints that lie (don't match runtime behavior)

Q15: When should I use pipeline patterns (FP composition) vs method chaining (OOP)?​

Simple answer:

  • Pipeline (FP): Independent steps, data flows through functions
  • Method chaining (OOP): Object modifies itself and returns self

Pipeline pattern:

# Data flows through independent functions
def read_file(filename) -> str: ...
def parse_csv(text: str) -> list[dict]: ...
def filter_active(rows: list[dict]) -> list[dict]: ...
def calculate_totals(rows: list[dict]) -> list[dict]: ...

def process_pipeline(filename):
return (
read_file(filename) # str
| parse_csv # list[dict]
| filter_active # list[dict]
| calculate_totals # list[dict]
)

# Each function is independent, testable

Method chaining (OOP):

class QueryBuilder:
"""Fluent interface - methods return self"""
def __init__(self):
self._conditions = []

def where(self, column, value):
self._conditions.append(f"{column} = {value}")
return self # Return self for chaining

def order_by(self, column):
self._conditions.append(f"ORDER BY {column}")
return self

def limit(self, n):
self._conditions.append(f"LIMIT {n}")
return self

def build(self):
return "SELECT * FROM users " + " ".join(self._conditions)

# Usage
query = (QueryBuilder()
.where("tenant_id", "acme")
.where("active", True)
.order_by("created_at")
.limit(10)
.build())
# SELECT * FROM users WHERE tenant_id = acme WHERE active = True ORDER BY created_at LIMIT 10

When to use pipeline:

  • Data transformation (ETL, CSV processing)
  • Stateless operations
  • Need to reuse steps independently
  • Easy testing (each function isolated)

When to use chaining:

  • Building complex queries (SQL builders)
  • Configuration objects
  • Stream processing where state accumulates
  • Fluent APIs (DSL-like)

Hybrid example:

# OOP object with FP pipeline methods
class DataProcessor:
def __init__(self, data: list[dict]):
self.data = data

def pipeline(self):
"""Returns pipeline of functions to apply"""
return (
self.data
| filter_active
| sort_by_date
| calculate_metrics
)

def process(self):
return list(self.pipeline())

processor = DataProcessor(rows)
result = processor.process()

🔍 What interviewers test: Understanding of composability, fluent interfaces, separation of concerns.

❌ Common mistakes:

  • Long chains that are hard to debug
  • Pipeline functions with side effects
  • Mixing both confusingly
  • Not knowing when each improves readability

Q16: State machines: OOP vs FP implementation​

Simple answer: State machines model workflows with states and transitions. OOP uses polymorphism (each state is a class). FP uses pattern matching (case/switch on state + data).

OOP state machine (State pattern):

from abc import ABC, abstractmethod

# Each state is a class
class State(ABC):
@abstractmethod
def handle(self, context):
pass

class ReadyState(State):
def handle(self, context):
print("Starting...")
context.state = RunningState()

class RunningState(State):
def handle(self, context):
print("Running...")
context.state = PausedState()

class PausedState(State):
def handle(self, context):
print("Paused")
context.state = ReadyState()

# Context carries state
class Workflow:
def __init__(self):
self.state: State = ReadyState()

def transition(self):
self.state.handle(self) # Delegates to current state

# Usage
wf = Workflow()
wf.transition() # Ready -> Running
wf.transition() # Running -> Paused
wf.transition() # Paused -> Ready

FP state machine (pattern matching):

from dataclasses import dataclass
from typing import Literal

StateType = Literal["ready", "running", "paused"]

@dataclass
class Workflow:
state: StateType = "ready"
data: dict = None

def transition(self):
"""Pure function returns new state"""
if self.state == "ready":
return Workflow(state="running", data=self.data)
elif self.state == "running":
return Workflow(state="paused", data=self.data)
elif self.state == "paused":
return Workflow(state="ready", data=self.data)

# Usage - immutable, track history
wf = Workflow()
print(wf.state) # "ready"

wf = wf.transition()
print(wf.state) # "running"

wf = wf.transition()
print(wf.state) # "paused"
# Old states still exist if stored

Which for backend?

  • OOP: Complex state with behavior per state (e.g., payment processing with different logic per state)
  • FP: Simple state transitions, need audit trail (immutability = history preserved)

Real backend example - order processing:

# OOP: Each state class encapsulates behavior
class OrderState(ABC):
@abstractmethod
def ship(self, order): ...
@abstractmethod
def cancel(self, order): ...

class PendingState(OrderState):
def ship(self, order):
order.state = ShippedState()
order.shipped_at = datetime.now()

def cancel(self, order):
order.state = CancelledState()
order.cancelled_at = datetime.now()

class Order:
def __init__(self):
self.state: OrderState = PendingState()

def ship(self):
self.state.ship(self) # Delegates to current state

# FP: Pattern matching on state
@dataclass
class Order:
status: Literal["pending", "shipped", "cancelled"]
items: list[str]

def ship(self):
if self.status != "pending":
raise InvalidTransitionError("Can only ship pending orders")
return Order(status="shipped", items=self.items) # New object

def cancel(self):
if self.status not in ["pending", "shipped"]:
raise InvalidTransitionError("Cannot cancel")
return Order(status="cancelled", items=self.items)

🔍 What interviewers test: Pattern matching vs polymorphism, state management, workflow design.

❌ Common mistakes:

  • Giant if/elif chains instead of proper state pattern
  • States that can skip invalid transitions
  • Not validating state transitions
  • Mixing state logic with business logic

Advanced Comparison: Python-Specific Considerations​

Python Is a Hybrid Language​

Python supports both FP and OOP. Understanding when to use each is key:

# Pythonic hybrid: dataclass (OOP) + pure functions (FP)
from dataclasses import dataclass
from typing import Callable

@dataclass(frozen=True) # Immutable dataclass (FP!)
class Money:
"""Value object - immutable (FP principle)"""
amount: int
currency: str

def __add__(self, other):
# Returns new object, doesn't modify (FP)
return Money(self.amount + other.amount, self.currency)

# Pure functions operating on data classes
def calculate_total(items: list[Money]) -> Money:
return sum(items, Money(0, "USD")) # Pure function

# Class for stateful service
class ShoppingCart:
def __init__(self):
self._items: list[Money] = [] # Mutable state

def add(self, item: Money):
self._items.append(item) # Mutation (OOP)

def total(self) -> Money:
return calculate_total(self._items) # FP function!

Key insight: Use immutable data classes (FP) + stateful services (OOP).


Python Gotchas: FP vs OOP​

  1. Mutable default arguments (OOP trap):
# ❌ BAD: Shared mutable default
class Tenant:
def __init__(self, name, users=[]): # Same list for ALL instances!
self.users = users

# ✅ GOOD: None then create
class Tenant:
def __init__(self, name, users=None):
self.users = users or [] # New list per instance
  1. Late binding closures (FP trap):
# ❌ BAD: Closure captures variable by reference
functions = []
for i in range(3):
def func():
return i # All return 2 (last value)
functions.append(func)

# ✅ GOOD: Capture value at definition time
functions = []
for i in range(3):
def func(i=i): # Default captures current i
return i
functions.append(func)
  1. self in closures:
class Counter:
def __init__(self):
self.count = 0

def make_incrementer(self):
def increment():
self.count += 1 # Captures self, modifies state
return self.count
return increment

# FP alternative: no self captured
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment

Summary Cheat Sheet​

Question: "Functional or OOP?"

Answer template:

"It depends. I use:

  • Functions for: stateless logic, data pipelines, utilities
  • Classes for: domain models, stateful services, polymorphism
  • Hybrid in practice: classes for structure, functions for behavior

For web backends specifically, I tend towardFP for business logic (easier to test) and OOP for models (clearer relationships)."

When interviewer asks for tradeoffs:

ConcernFunctional BetterClass-Based Better
Testing✅ True⚠️ Needs design
Concurrency✅ No locks needed⚠️ Needs synchronization
Readability✅ for transforms✅ for entities
Performance⚠️ Copy overhead✅ In-place updates
State management❌ Clunky✅ Natural

Final advice: Be pragmatic. Use what makes code clearer for your team. Backend interviews test understanding, not dogma.


Last updated: May 2026