Member-only story

Defying Convention: Inheritance in Functional Programming Paradigm

Break free from classic OOP thinking and embrace alternative patterns

Max N
2 min readApr 4, 2024
Photo by José on Unsplash

Functional programming (FP) differs significantly from object-oriented programming (OOP). Traditional concepts like inheritance don’t fit neatly within the confines of pure functional paradigms. Nevertheless, there exist creative techniques mimicking OOP inheritance using FP tools like higher-order functions and closures.

Consider the following case study, where we simulate inheritance by composing functions instead of deriving classes. Assume we’d like to represent geometric figures, each having a corresponding area formula and label.

const circle = radius => ({
label: 'Circle',
area() {
return Math.PI * radius * radius;
}
});

const rectangle = (width, height) => ({
label: 'Rectangle',
area() {
return width * height;
}
});

const triangle = (base, height) => ({
label: 'Triangle',
area() {
return 0.5 * base * height;
}
});

const shapes = [circle, rectangle, triangle];

shapes.forEach(factoryFn => {
const shapeInstance = factoryFn(Math.random() * 10);
console.log(`Created ${shapeInstance.label} with random side lengths:`);
console.log(`Area: ${shapeInstance.area()} \n`);
});

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet