O.O.P. and Functional Programming in 5 Lines Of Code
Let’s discuss the differences (and similarities) between functional and object-oriented programming.
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…