Programming Paradigms
A paradigm is a set of assumptions about where state lives and how computation proceeds. Most modern languages are multi-paradigm, so the useful question is not “which is best” but “which fits this problem”.
The 60-second answer
Section titled “The 60-second answer”Imperative code says how: assign, loop, mutate. Declarative code says what: SQL, regex,
map. Object-oriented programming organises code around objects that own state and behaviour, giving encapsulation and polymorphism. Functional programming organises code around pure functions and immutable data, giving easier reasoning and safer concurrency. Real code mixes them: OOP for the domain model, functional style inside methods, because pure transformations are easier to test.
The four families
Section titled “The four families”| Paradigm | Core idea | Seen in | Strength | Weakness |
|---|---|---|---|---|
| Imperative | Statements changing state | C, loops | Direct control | State sprawl |
| Declarative | Describe the result | SQL, regex | Concise, optimisable | Hides cost |
| Object-oriented | Objects own state + behaviour | Ruby, Java | Encapsulation, polymorphism | Inheritance tangles |
| Functional | Pure functions + immutable data | Haskell, Elixir | Testability, concurrency | Allocation cost |
total = 0[1, 2, 3].each { |n| total += n } # imperative: how[1, 2, 3].sum # declarative: whatDeclarative code leaves the loop to the library, which may know a faster way — the argument for sum,
group_by and SQL over hand-written loops.
Object-oriented programming
Section titled “Object-oriented programming”Four pillars, though only the first two are distinctive:
- Encapsulation: hide state behind methods;
attr_readervsattr_accessoris a design decision. - Polymorphism: the same call means different things per type —
animal.speakforDogandCat. - Abstraction: expose the concept, hide the mechanism. A
PaymentGatewayhides Stripe. - Inheritance: reuse by specialisation. Powerful and overused.
class Shape def area = raise NotImplementedErrorend
class Circle < Shape def initialize(radius) = @radius = radius def area = Math::PI * @radius**2end
[Circle.new(2)].sum(&:area) # => 12.566...| Letter | Principle | The smell it fixes |
|---|---|---|
| S | Single responsibility | A class with “and” in its description |
| O | Open/closed | Every new type edits a case statement |
| L | Liskov substitution | A subclass that raises on an inherited method |
| I | Interface segregation | Fat interfaces where implementors stub most methods |
| D | Dependency inversion | Business logic constructing its own database connection |
Liskov is the one interviewers probe. If Square < Rectangle and setting width also changes
height, a Square breaks every caller that assumed Rectangle semantics — so “is-a” is not
sufficient grounds for inheritance.
Composition over inheritance
Section titled “Composition over inheritance”Inheritance couples you to the parent’s implementation forever and allows one axis of variation.
Composition assembles independent behaviours. Ruby’s answer to multiple inheritance is modules:
include puts the module after the class in the lookup chain, prepend puts it before, extend
adds the methods to the object’s singleton class.
module Notifiable def notify(message) = "#{email}: #{message}"end
class User include Notifiable attr_reader :email def initialize(email, notifier: nil) = (@email, @notifier = email, notifier) def welcome = @notifier ? @notifier.deliver(to: email) : notify("welcome")endFunctional programming
Section titled “Functional programming”- Pure function: same input, same output, no side effects.
- Referential transparency: a call can be replaced by its result without changing behaviour.
- Immutability: data is never modified; new data is produced (
#freeze, frozen literals). - Higher-order functions: functions take and return functions.
def with_vat(prices) prices.map { |p| (p * 1.2).round(2) } # no mutation, composableend
double = ->(x) { x * 2 }increment = ->(x) { x + 1 }(double >> increment).call(5) # => 11
(1..Float::INFINITY).lazy.map { |n| n * n }.select(&:even?).first(3).to_a # => [4, 16, 36]Choosing a style
Section titled “Choosing a style”OOP for rich domain behaviour and invariants, functional for transformation pipelines and concurrent shared state, declarative for queries, imperative for tight numeric loops.
Follow-up questions
Section titled “Follow-up questions”- Give an example where inheritance is right and one where it is not.
- What does a Liskov violation look like in a code review?
- How does immutability help concurrency, and what does it cost?
- Is Ruby a functional language? Justify your answer.
- How would you refactor a 200-line method mixing I/O, validation and persistence?
Common traps
Section titled “Common traps”- Treating SOLID as rules. They are heuristics; applying all five produces interfaces nobody needs.
- “Functional means no classes.” You can write functional Ruby with classes.
- Confusing declarative with “no loops”.
mapis still a loop; the difference is who controls it. - Thinking immutability is free. Copying on every change can dominate the runtime.