O.O.P. and Functional Programming in 5 Lines Of Code

Emanuel Trandafir
Javarevisited
Published in
5 min readMar 22, 2023

--

Let’s discuss the differences (and similarities) between functional and object-oriented programming.

image generated on https://imgflip.com/

In this concise article, we’ll explore fundamental distinctions among procedural programming, functional programming, and object-oriented programming. While our focus remains straightforward, we’ll only graze the surface of this multifaceted subject. For this reason, we’ll use a very simple example, which comprises a mere five lines of code.

Imperative Style

Let’s write a simple function that simulates a coin flip and returns its result:

public String coinFlip() {
int randomNumber = new Random().nextInt();
if (randomNumber % 2 == 0) {
return "Heads";
}
return "Tails";
}

While the example presented here is straightforward, it showcases an imperative approach to programming. Procedural code typically relies on control structures like loops and conditional statements to execute code, and local or global variables to store, modify and share the data.

In this particular case, a random number is stored as an integer variable and later referenced in an if statement. However, even in this simple instance, there exists a temporal coupling between the two lines of code; that is, we must assign the randomNumber

--

--

Emanuel Trandafir
Javarevisited

Hi, I'm Emanuel Trandafir, a Java developer from Romania. I have a strong passion for clean code, software design, and unit testing.