The Code Codex
Theme
← Notes / Paradigms

note · text08 Oct 2024 · 2 min

Paradigms

What does it mean?

By definition, a paradigm is a mental framework composed of theories, experiences, methods, and instruments that serves to organize thought and, in a certain way, reality and its events. It is the representation of a standard to be followed.

What about a programming paradigm?

Following the definition of the word itself, a programming paradigm is nothing more than how a programming language structures its parts, providing tools so that programmers can model a system or structure. Given the structure proposed by the paradigm, it is up to the user of that structure (in this case, the programmer) to choose the paradigm that best suits the problem.

What programming paradigms exist?

There are several paradigms, some more common than others, and some that coexist within the same programming language. The most widely used today are object-oriented and functional.

ParadigmCore ideaExamples
Imperative / proceduralA sequence of commands that change the program’s stateC, Go, Pascal
Object-orientedData and behavior together in objects that exchange messagesJava, C#, Smalltalk
FunctionalPure functions and immutable data; the result depends only on the inputHaskell, Elixir, Clojure
DeclarativeYou describe what you want, not how to get itSQL, HTML, CSS
LogicFacts and rules; the engine deduces the answersProlog
Event-drivenThe flow is driven by events (clicks, messages)JavaScript in the browser

The same task, summing the even numbers in a list, in two styles:

// imperative: says step by step how to do it
int total = 0;
for (int n : numbers) {
if (n % 2 == 0) total += n;
}
// functional/declarative: describes the result
int total = numbers.stream().filter(n -> n % 2 == 0).mapToInt(Integer::intValue).sum();

There you go, this is the basic idea about paradigms. It’s worth noting that not all languages will implement a paradigm to the letter. For example, Golang does not support inheritance, thus not meeting 100% of the requirements of an object-oriented language, but that’s okay. In Java, functional programming arrived as an adaptation of the language (Java 8): there are no real first-class functions, but rather “Functional Interfaces”. Lambdas are implementations of those interfaces under the hood, and it works. Is it better than Haskell or another functional language? Maybe. Don’t get into arguments about which is the best paradigm of all just to compare; it’s a waste of time. Try to understand what is best for what needs to be solved.