1. Home
  2. Explore
  3. Computer Science
  4. Programming Paradigms

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Programming Paradigms

Four Programming Paradigms: Study Notes

Programming paradigms are different ways of organizing a program and describing how a problem should be solved. Learning more than one paradigm helps separate programming concepts—such as conditions, collections, arithmetic, and memory—from the particular syntax of any one language.

The same problem can look very different in different paradigms. A cashier’s task of making change provides a useful comparison: the underlying goal stays the same, but each paradigm emphasizes a different way to represent the problem.


1. Object-Oriented Programming

Core idea

Object-oriented programming (OOP) organizes programs around objects. An object combines:

  • State: data associated with the object, such as fields, attributes, or instance variables.

  • Behavior: operations the object can perform, usually represented by methods.

Objects are generally created as instances of classes. A class defines what data and behavior its instances have.

Objects interact by sending messages—that is, by calling methods on one another. For example, asking an array for its length sends the array a request; the array calculates and returns the result.

In Ruby, objects can represent values as well as more complex entities. In Ruby’s particularly object-oriented model, even values such as false are objects, and classes themselves are objects.

Encapsulation and state

A central OOP principle is that an object should usually manage its own internal state. Other parts of a program ask the object to perform an operation rather than directly changing its internal data.

For example, a bank account can store its balance internally and expose methods to deposit or withdraw money:

  • A deposit operation increases the balance.

  • A withdrawal operation decreases the balance.

  • A balance-reading method can allow the balance to be inspected without allowing outside code to set it directly.

This separation protects the object’s state from arbitrary changes. The object is responsible for keeping its data consistent.

Encapsulation means grouping state with the behavior that operates on it, while controlling how other parts of a program access or modify that state.

Representing money

Money should generally be stored as an integer number of the smallest currency unit—for example, cents—rather than as a floating-point number. Floating-point representations can introduce rounding errors because many decimal fractions cannot be represented exactly in binary.

For calculations, a value such as 4.50 can be stored as 450450450 cents. The same principle applies to change-making: amounts owed, amounts tendered, and denominations should use integer units.

Example: modeling a bank account

A bank-account class might have:

  • An internal balance initialized to zero.

  • A read-only balance accessor.

  • A deposit method that adds an amount to the balance.

  • A withdraw method that subtracts an amount from the balance.

The object’s balance is its state; initialization, deposit, withdrawal, and balance access are its behaviors.

Example: making change with an object

A cash register can be modeled as an object containing a cash drawer: an ordered collection of available denominations, such as bills and coins.

A change-making method can receive:

  • The amount the customer owes.

  • The amount the customer tendered.

It then calculates the change due:

change due=amount tendered−amount owed\text{change due} = \text{amount tendered} - \text{amount owed}change due=amount tendered−amount owed

A typical greedy procedure scans denominations from largest to smallest:

  1. If the current denomination is larger than the remaining change, skip it and examine the next smaller denomination.

  2. Otherwise, use that denomination and subtract its value from the remaining change.

  3. Continue until no change remains.

The resulting collection describes which bills and coins the cashier should give.

This approach assumes that denominations are sorted from largest to smallest. It also assumes that the denominations and their available quantities permit the requested change. If the drawer contains limited quantities, the program must track those quantities as well.

Strengths and limitations of OOP

  • Models entities naturally: Objects can represent familiar things, such as accounts, chairs, or cash registers, with both attributes and behavior.

  • Encourages reuse: Standard-library objects such as arrays, hashes, and strings can be used across many programs.

  • Supports testing in isolation: Individual objects can be tested for correct behavior, followed by tests of how objects interact.

  • Can be awkward for some problems: A change-making algorithm is mainly a sequence of calculations and decisions. It does not naturally benefit from bundling state and behavior into several interacting objects.


2. Functional Programming

Core idea

Functional programming organizes computation around functions. A function takes input data and produces output data.

In pure functional programming, functions do not modify their inputs or store changing state. Their output depends only on their input: the same input always produces the same output.

A pure function can be understood as a transformation from input data to output data, without hidden dependence on program history or mutable state.

If a function receives a list and needs to change it, pure functional style produces a new list rather than modifying the original one. This avoids side effects—changes that are observable outside the function.

Functional programming separates data from the procedures that transform it. This contrasts with OOP, which commonly groups data and the methods operating on that data within objects.

Racket and prefix notation

Racket belongs to the Lisp family of languages. Lisp-family languages commonly use prefix notation, placing the operator before its arguments.

For example, addition of three and five is written conceptually as:

(+ 3 5)

An operation can accept several arguments, such as multiplying one, two, and three:

(* 1 2 3)

Nested expressions use parentheses to make the order of operations explicit. For instance, two calculations can be combined by placing their expressions inside an outer expression. This makes the structure of the calculation visible without relying on conventional operator precedence.

A function definition names the function, lists its arguments, and supplies a body. A function call places the function name before its arguments.

Conditionals

Racket’s cond form evaluates tests in order and executes the result associated with the first true test. It also supports a final “otherwise” case.

For absolute value, the cases are:

  1. If xxx is positive, return xxx.

  2. If xxx is zero, return zero.

  3. Otherwise, xxx is negative, so return −x-x−x.

This shows that conditionals are a general programming concept even though their syntax differs between languages.

Lists

Lists are central to Lisp-family languages. A list can be written as a sequence of items inside parentheses. A notation mark distinguishes a literal list from a function call; without it, a parenthesized expression is generally interpreted as an operation.

The basic list operations are:

  • car: returns the first element of a list.

  • cdr: returns the rest of the list after the first element.

  • cons: constructs a new list by adding an item to the front of another list.

The first element is also called the head; the remainder is called the tail. These operations support recursive processing of lists: inspect the first element, then process the rest.

Recursion

Functional programs often express repetition through recursion: a function calls itself on a smaller or simpler input.

A recursive definition needs:

  • Base case: a simple input whose result is known directly.

  • Recursive case: a rule that reduces the problem to a smaller instance of itself.

For factorial:

  • The factorial of zero or one is one.

  • For larger positive nnn, the factorial is nnn multiplied by the factorial of n−1n-1n−1.

In mathematical notation:

n!={1,n≤1n⋅(n−1)!,n>1n! = \begin{cases} 1, & n \leq 1 \\ n \cdot (n-1)!, & n > 1 \end{cases}n!={1,n⋅(n−1)!,​n≤1n>1​

For Fibonacci numbers, the initial cases are zero and one; each later value is the sum of the preceding two:

Fn={0,n≤01,n=1Fn−1+Fn−2,n>1F_n = \begin{cases} 0, & n \leq 0 \\ 1, & n = 1 \\ F_{n-1} + F_{n-2}, & n > 1 \end{cases}Fn​=⎩⎨⎧​0,1,Fn−1​+Fn−2​,​n≤0n=1n>1​

These definitions demonstrate how recursive code can mirror mathematical definitions. In practice, naïve recursive Fibonacci can repeat many calculations, so an implementation may need memoization or another efficiency improvement.

Example: making change functionally

A functional change-making function can receive:

  • An amount to make.

  • A list of available denominations, ordered from largest to smallest.

It can return a list of denominations to use, or a failure value if the change cannot be made.

A recursive strategy is:

  1. If the remaining amount is zero, return an empty list: no more coins are needed.

  2. If there are no denominations left while the amount is nonzero, report failure.

  3. If the largest remaining denomination is greater than the amount, skip it and recursively try the remaining denominations.

  4. Otherwise, use that denomination and recursively make change for the amount left over. Keep the same denomination available because it may be used again.

This style returns new results rather than changing a cash-drawer object or modifying an existing list.

Strengths of functional programming

  • Predictable behavior: Pure functions produce the same result for the same input.

  • Simpler testing: Tests can supply input and check output without first arranging hidden object state.

  • Easier reuse: A pure function is less dependent on the surrounding program’s context.

  • Helpful for concurrent work: Pure functions avoid many problems caused by multiple operations changing shared state. This can reduce the need for locks, though real functional languages and programs may still use state or require concurrency coordination.

  • Concise expression: Functional code, especially in Lisp-family languages, can express some recursive algorithms compactly.


3. Logic and Constraint Programming

Core idea

Logic programming describes facts and relationships, then asks the system to find values that make a query true. Rather than specifying every step of how to solve a problem, a program specifies what must be true.

Prolog is a logic-programming language based on formal logic. Its programs contain facts and rules, and users submit queries about them.

For example, a knowledge base might contain facts about family relationships or geographic borders. A query asks whether a relationship holds or which values would make it hold.

Facts, rules, and queries

A Prolog fact states a relationship and ends with a period. For example, a fact can state that Washington borders Oregon.

A rule defines a relationship in terms of other facts or rules. The general structure means:

A relationship holds if the conditions following the rule are satisfied.

Prolog commonly uses:

  • Lowercase names for constants, such as locations or people.

  • Capitalized names for variables, such as X or Y.

  • A logical implication marker to introduce a rule.

  • A period to end facts and rules.

A rule for adjacency can say that XXX and YYY are adjacent if they share a border. If border facts are stored in only one direction, the rule must also account for the reverse direction when adjacency is intended to be symmetric. Prolog uses only what has been stated or defined; it does not automatically infer that a relationship is reversible.

Pattern matching and unification

Prolog searches for values that make a query or rule true. It does this through unification: matching expressions by finding consistent substitutions for variables.

For example, a query asking who is the mother of Bart asks Prolog to find a value for a variable that makes the mother relationship true. If the facts include that Marge is Bart’s mother, Prolog can return Marge.

A variable can appear in different positions in a query. Asking “Who is Bart’s mother?” and asking “Whose mother is Marge?” are different queries over the same relation.

This makes logic programs relational: a relationship can often be queried in more than one direction, rather than having a single fixed input and output.

Family relationships as rules

A family knowledge base can record parent relationships as facts. A sibling rule can then define two people as siblings if they share a mother or share a father, provided they are not the same person.

The rule’s conditions express the relationship, while Prolog searches for people satisfying them. A query can ask for sibling pairs, and the system attempts to find substitutions that make the rule true.

Prolog’s results depend on the facts and rules available. A sibling definition based only on shared mothers and fathers will not identify siblings unless the relevant parent facts have been supplied.

Lists and pattern matching

Prolog supports lists, including empty lists, lists of constants or numbers, and nested lists. It uses a pattern sometimes described as head–tail notation to split a list into its first item and its remainder.

For a list with first element FFF and remaining list RRR:

  • FFF matches the first item.

  • RRR matches the rest of the list.

This is conceptually similar to car and cdr in Lisp-family languages.

An underscore represents a value that is intentionally unused. It means that the program does not care what value appears in that position.

Example: membership in a list

A membership rule can be defined recursively:

  1. An item is a member of a list if it matches the list’s first element.

  2. An item is also a member if it is a member of the rest of the list.

The second case recursively examines progressively shorter lists. The process eventually either finds a matching element or reaches the empty list.

Example: making change as a relation

A Prolog change predicate can describe a relationship among three values:

  • The amount to make.

  • The list of available denominations.

  • The list of denominations used to make the amount.

Unlike a conventional function that returns a result, the relationship is expressed through all its arguments. This supports Prolog’s general ability to search for values that satisfy a relation.

The basic cases are:

  • An amount of zero is made using an empty list of coins, regardless of which denominations are available.

  • If the amount is positive and there are no usable denominations, no solution exists.

  • If the first denomination is no greater than the amount, it may be used. The remaining amount is then solved recursively, and the same denomination may be reused.

  • If the first denomination is too large, it can be skipped and the problem solved using the remaining denominations.

The rules express conditions that must hold, and Prolog searches for a list satisfying them. As with the functional example, denomination order and assumptions about available quantities matter. A simple list of denominations typically represents values that can be reused without a limited stock count.

Constraint solving

Logic programming can also be used for constraint problems, where the goal is to find an assignment satisfying a collection of requirements.

Scheduling is a typical example. Constraints might describe:

  • How long each activity takes.

  • How often it must recur.

  • Which times are unavailable.

  • Which activities require the same limited resource.

A logic or constraint solver searches for a schedule that satisfies the conditions. This is different from manually writing an exact sequence of scheduling steps.

Strengths and challenges

  • Flexible queries: Relations may be queried in more than one direction.

  • Useful for search and constraints: The system can search for assignments satisfying many conditions.

  • Concise descriptions: A relationship can sometimes be represented with a small set of facts and rules.

  • Different mental model: Prolog programs are not simply lists of instructions, so they can be difficult to read and debug for programmers accustomed to step-by-step procedures.

  • Requires suitable rules: Prolog can only infer what follows from the rules and facts provided; missing or incomplete relationships lead to missing results.


4. Procedural Programming and Assembly

Core idea

Procedural programming organizes a program as a sequence of instructions: perform one operation, then another, then another. It often relies on procedures, variables, conditionals, loops, and changes to stored values.

A simple “Hello, world” program and many scripts are procedural: they execute a series of steps in a defined order.

Procedural style is common across languages and is not limited to assembly. Assembly makes this approach especially visible because it exposes low-level operations and provides relatively few built-in abstractions.

Assembly and machine-level operations

Assembly languages represent operations close to the instructions executed by a processor. Different processors have different assembly languages. A simplified teaching assembly may provide only a small set of registers and operations.

In the teaching assembly described here, the main registers are:

  • A register: can hold a value or a memory address.

  • D register: a data register used in calculations.

  • M: shorthand for the memory cell addressed by the value currently in A.

The notation distinguishes the address held in A from the contents of the memory location at that address. If A contains address 000, then M refers to the contents of memory cell 000.

The available arithmetic and logic operations are limited to operations such as addition, subtraction, incrementing or decrementing, negation, bitwise NOT, bitwise AND, and bitwise OR. The teaching assembly does not provide built-in multiplication, division, or list structures. More complex behavior must be constructed from simpler instructions.

Assignment and constants

Instructions can store a computed value in a register or in memory. A constant-loading notation places a value into the A register. The program can then move that value into another register or into a memory cell.

Labels name locations in the program. They allow instructions to refer to a point in the code without requiring the programmer to calculate its numeric address manually.

Conditional and unconditional jumps

Low-level assembly does not generally provide a high-level if or while construct. Instead, it uses jumps:

  • A conditional jump changes the next instruction only if a specified condition is met.

  • An unconditional jump always transfers control to its target.

In the teaching assembly, jump tests compare a value against zero. Examples include jumping when a value is greater than zero, equal to zero, or less than zero. These limited tests can be combined to implement more complex decisions and loops.

Example: adding two numbers

A basic addition routine can:

  1. Load one constant into the A register.

  2. Copy it into D.

  3. Load the second constant into A.

  4. Add D and A.

  5. Store the result in a memory cell.

The example illustrates the low-level pattern of explicitly loading values, calculating with registers, and storing results.

Example: summing a sequence with a loop

A loop that sums the numbers from one through five can use memory cells for both the accumulator and the counter:

  1. Initialize the accumulator to zero.

  2. Initialize the counter to five.

  3. Add the counter to the accumulator.

  4. Decrement the counter.

  5. If the counter is still positive, jump back to the start of the loop.

  6. Otherwise, continue to the end of the program.

The high-level idea of a loop is built from memory operations, arithmetic, a conditional jump, and a label.

Example: making change in assembly

Because the teaching assembly has no list type, the change-making problem can represent its data in fixed memory locations. For example:

  • One cell stores the amount of change to make.

  • Several cells store denomination values, such as quarters, dimes, nickels, and pennies.

  • Additional cells store how many of each denomination will be used.

The algorithm must explicitly manage these locations. For a denomination, it can subtract that value from the remaining amount and test whether the result is negative:

  • If it is negative, that denomination is too large for the remaining amount, so the program moves to a smaller denomination.

  • If it is not negative, the program records that denomination, updates the remaining amount, and repeats.

This illustrates the amount of detail required when higher-level structures such as lists, objects, and loops are not available as built-in language features.

Strengths and limitations of procedural programming

  • Direct sequence of operations: The program’s execution order is explicit.

  • Easy to start with: Many learners naturally think in steps, making basic procedural programs approachable.

  • Useful for scripting and low-level control: A sequence of commands is often appropriate when automating tasks or controlling hardware.

  • Assembly is highly constrained: Programmers must manage registers, memory, arithmetic, and branching explicitly, making it verbose and easy to get wrong.

  • Limited abstraction: Common structures such as lists and high-level loops must be represented manually in a low-level language.


5. Comparing the Paradigms

The same change-making task emphasizes different concepts in each approach:

Object-oriented approach

  • Represents a cash register as an object.

  • Stores the drawer as object state.

  • Uses a method to calculate change.

  • Emphasizes encapsulation and interaction with objects.

Functional approach

  • Represents change-making as a function from input data to output data.

  • Uses recursion and immutable lists.

  • Emphasizes predictable transformations without modifying state.

Logic-programming approach

  • Represents change-making as a relationship among amount, available denominations, and chosen coins.

  • States the conditions under which a solution is valid.

  • Lets the system search for values satisfying those conditions.

Procedural and assembly approach

  • Represents values in registers and memory.

  • Gives explicit instructions for each calculation and branch.

  • Emphasizes execution order and direct control of program state.

These approaches are not simply different syntaxes for identical ideas. Each directs attention toward a different way of structuring a solution: objects and state, functions and transformations, relations and constraints, or ordered instructions and control flow.


6. Broader Lessons About Programming Languages

Many programming languages share underlying concepts even when their syntax looks very different. Conditions, arithmetic, collections, and storing or retrieving values appear in many languages, but each language may express them differently.

Understanding these concepts independently of syntax makes it easier to learn additional languages. Once the underlying ideas are familiar, a new language’s notation is less likely to make those ideas seem entirely new.

Different languages and paradigms are also suited to different kinds of problems. A design that feels natural in one paradigm may be awkward in another. Choosing an approach involves considering the structure of the problem, the kinds of data involved, and whether the task is best expressed as object interaction, data transformation, constraint satisfaction, or a sequence of operations.

Learning several paradigms helps programmers recognize both what programming languages share and what each way of organizing a program makes easier or harder to express.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent