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

Speaker 1Speaker 2

Programming Paradigms

12:52
0:00-12:52
  1. Simon

    Today we’re comparing four programming paradigms by asking each one to solve the same small problem: how does a cashier calculate change? The original talk grew out of a college course that surveyed computer science and spent several weeks learning different languages by solving problems in each. The big lesson was abstraction: once you understand an idea like a condition, a collection, or storing data, it stops being tied to one language’s syntax.

  2. Michael

    And that makes learning another language less intimidating. The syntax may look unfamiliar, but many underlying concepts recur in different forms. At the same time, the paradigms really do differ, and different languages are better suited to different kinds of problems. We’ll see both the similarities and the differences by moving through object-oriented, functional, logic, and procedural programming.

  3. Simon

    First, object-oriented programming, illustrated with Ruby. In Ruby, everything is an object: values like false and nil, and even classes themselves. An object encapsulates state—data such as fields or instance variables—and behavior, usually expressed as methods.

  4. Michael

    The object is generally responsible for changing its own internal state. In Ruby, a method can refer to its object as self. Objects interact through message passing: if you ask an array for its length, you send it the length message, and the array returns a result based on its own contents.

  5. Simon

    A bank account is a familiar example. We can define a BankAccount class with an internal balance, initialized to zero. We might expose a reader so other code can inspect the balance, but not let outside code set it directly. And for money, the example represents amounts as integer cents rather than floating-point numbers.

  6. Michael

    Then the account can offer deposit and withdraw methods. Deposit adds an amount to the balance; withdraw subtracts one. The balance is the state, while initialize, deposit, and withdraw are behavior. Other code sends a message with an amount and relies on the account object to update itself appropriately.

  7. Simon

    That design reflects some strengths of object-oriented programming. Objects can model familiar things that have both properties and actions, like a chair with a color that holds someone up. They’re also reusable: arrays, strings, and hashes provide behavior that many programs can rely on rather than reimplementing each time.

  8. Michael

    And objects can be tested in isolation: first check that an object behaves correctly, then test how it interacts with other objects. But the change-making example isn’t a particularly natural object-oriented problem. That’s useful to notice too: a paradigm can be valid without being the best fit for every task.

  9. Simon

    For the Ruby cash register, imagine a drawer organized from largest denomination to smallest: twenties, tens, fives, ones, then quarters, dimes, nickels, and pennies. The method receives the amount owed and the amount tendered by the customer. It subtracts the amount owed from the tendered amount to find the change due.

  10. Michael

    The method then walks through the denominations, keeping an index for the current slot and a list of the bills and coins to give back. While change remains, if the current denomination is too large, it advances to the next one. Otherwise, it uses that denomination, records it, subtracts its value from the remaining change, and continues.

  11. Simon

    That approach assumes the denominations are sorted largest to smallest. It also describes which denominations to use, rather than tracking how many of each coin or bill are actually in the drawer; a fuller implementation could track those counts. The code is a loop that changes variables and builds a result, which is why the speaker notes it isn’t an especially elegant demonstration of object-oriented design.

  12. Michael

    Next is functional programming, shown with Racket, a language in the Lisp family. The focus here is pure functional programming: functions take data in and return data, without storing state or mutating the data they were given. So if a function receives a list, it returns a new result rather than changing the original list.

  13. Simon

    That gives pure functions a useful property: the output depends only on the input, not on what happened earlier. Give the same function the same input and it produces the same result. Compared with object-oriented programming, state and behavior are treated separately here instead of being bundled together inside an object.

  14. Michael

    Racket’s syntax may look unusual if you’re used to Ruby. It uses prefix notation: instead of writing three plus five, you write a plus sign followed by three and five in parentheses. The same operation can take several arguments, so multiplying one, two, and three is written with one multiplication symbol and all three numbers.

  15. Simon

    Nesting parentheses makes compound expressions explicit. You can multiply three and five, subtract six from ten, and then add those results. That explicit nesting can make the order of operations especially clear. To define a function, you write define, the function name and its arguments, and then the function body—for example, square takes n and multiplies n by itself.

  16. Michael

    For conditionals, the example uses cond, which is similar to a case statement. To calculate an absolute value, return x if it’s positive, return zero if it’s zero, and otherwise return the negation of x. Lists are central in Lisp-family languages: you can get the first element with car, the rest with cdr, and build a list by using cons to attach an item to another list.

  17. Simon

    Recursion is another important tool in functional programming. Factorial can be defined with a base case—if n is one or less, return one—and a recursive case: multiply n by the factorial of n minus one. Fibonacci similarly has base cases for zero and one, then defines each later value as the sum of the two previous values.

  18. Michael

    Pure functional style can simplify testing because a test can provide input and check output without first arranging the state of an object. It can also make code easier to reuse in a different program, since there’s no surrounding state that the function depends on. And these programs can be very concise, though not everyone enjoys the style.

  19. Simon

    Now apply that to making change. The Racket function receives an amount x and a list of available denominations, ordered largest to smallest. If x is zero, it returns an empty list: no change is needed. If there are no denominations left while change is still needed, it returns false because it can’t make the amount.

  20. Michael

    There are two recursive choices. If the first denomination is larger than x, skip it and try to make x using the rest of the list. Otherwise, include that denomination in the result and recursively make change for the remainder, using the same denomination list again in case another bill or coin of that value is needed.

  21. Simon

    So the functional version expresses the problem through base cases and recursive cases, rather than updating an index and a running difference in a loop. It’s shorter than the Ruby version and can feel very natural if you’re comfortable with recursion and proofs by induction. But there’s another paradigm where the code can be even shorter—and more puzzling at first.

  22. Michael

    That’s logic programming, illustrated with Prolog. Instead of giving the computer a sequence of instructions describing how to solve a problem, you describe facts and relationships that should be true. Prolog then tries to find values that make those statements true, using the facts and rules you supplied.

  23. Simon

    A classic example is the statement that Socrates is a man and all men are mortal, so Socrates is mortal. In Prolog, facts end with a period; constants begin with lowercase letters, while variables begin with capitals. A rule describes a relationship—for example, X and Y are adjacent if a fact says they share a border.

  24. Michael

    Prolog uses pattern matching to see which facts fit a rule and what values can be assigned to its variables. It is also very literal: if you state that Washington borders Oregon, Prolog won’t automatically infer that Oregon borders Washington. You must encode the relationship in both directions if you want both queries to succeed.

  25. Simon

    Family relationships show how queries can work in different directions. If you state that Homer is Bart’s father and Marge is Bart’s mother, you can ask who Bart’s mother is—or ask who Marge is the mother of. Prolog can return answers, and if there are multiple answers, you can request another one.

  26. Michael

    Rules can combine several facts. For example, X and Y are siblings if they share a mother and are not the same person, or if they share a father and are not the same person. Prolog searches for values of the variables that make those conditions true. That ability to query relationships in different directions is one of logic programming’s distinctive strengths.

  27. Simon

    Prolog lists use a pattern-matching notation often called bar notation. You can think of a list as its first element and the rest: the first part matches one item, and the part after the bar matches the remaining list. An underscore means “don’t care”—a value that’s present but not needed by the rule.

  28. Michael

    The member rule illustrates recursion over a list. An item is a member if it matches the first element. Otherwise, it’s a member if it’s a member of the rest of the list. Logic programming can also express constraints, not just family relationships: Prolog has been used to schedule limited resources by stating requirements such as experiment durations, repetition schedules, and people’s availability.

  29. Simon

    For change-making in Prolog, the rule has three arguments: the amount, the list of available denominations, and the list describing how to make the change. There’s no separate return statement; the relationship among the arguments is what the program defines. One case says that change for zero is the empty list, regardless of what’s in the drawer.

  30. Michael

    The other cases use pattern matching and recursion. If the amount is large enough, use the first denomination, calculate the amount left, and recursively make change for that remainder with the same list. If you don’t use the first denomination, try the rest of the list instead. The code is compact, but encoding and understanding those relationships can be challenging.

  31. Simon

    The final paradigm is procedural programming, illustrated with a simple assembly language. Procedural code describes a sequence of steps—do this, then this, then that. Many people’s first program is procedural, and scripts often follow the same pattern. Assembly makes the style visible by giving you very few built-in operations.

  32. Michael

    In the assembly used here, there are two main registers: A and D. A can hold a value or an address; when it holds an address, M refers to the memory cell at that address. D is the data register. The language supports basic arithmetic and bitwise operations, but has no multiplication, division, or built-in list.

  33. Simon

    Constants are loaded into the A register with the at sign, and labels identify locations in the program. Jumps provide branching: you can jump when a value is greater than, less than, equal to, or otherwise related to zero, or jump unconditionally. Those are the available ways to change the flow of execution.

  34. Michael

    Even adding two numbers takes several steps: load one into A, move it to D, load the other into A, add, then store the result in memory. A loop that sums one through five uses memory cells for an accumulator and a counter. Each pass adds the counter to the accumulator, decrements the counter, and jumps back until the counter reaches zero.

  35. Simon

    For assembly change-making, the example has to represent everything in memory by hand. One location holds the amount to make, others hold the coin denominations, and additional locations hold how many of each coin to use. The quarter logic subtracts twenty-five from the remaining amount when possible, records another quarter, and repeats; otherwise, it moves on to dimes.

  36. Michael

    Assembly itself isn’t presented as something most programmers need to use every day. The broader procedural style, though, is straightforward and useful: specify the steps in order. The contrast is the point—each paradigm offers a different way to organize a solution, and the change problem that looked awkward for objects or verbose in assembly can be expressed differently with functions or logical relationships.

  37. Simon

    So the episode’s central lesson is to separate concepts from the syntax of any one language. Conditions, collections, arithmetic, and memory show up repeatedly, even when their expression changes. Learning another language can help those abstractions become clearer, and it can show you that different paradigms are useful for different tasks.

  38. Michael

    If you want to explore further, the talk recommends books on functional programming such as The Little Schemer and Structure and Interpretation of Computer Programs; Prolog books including The Art of Prolog; and The Elements of Computing Systems, also known as NAND to Tetris, for building an understanding of a computer from first principles. Seven Languages in Seven Weeks and Exercises in Programming Style offer more ways to compare languages and approaches.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent