Write code for humans!
Not for machines
Humans prefer this
Functional programming
const kmOfItalianDrivers = users
.filter(u => u.country === 'ITALY' &&
u.hasDriverLicence &&
u.age >= 18
)
.flatMap(u => u.cars)
.reduce((totalKm, car) => totalKm + car.km, 0);
Machines prefer this
Imperative code
let kmOfItalianDrivers = 0;
for (let i = 0; i < users.length; i++) {
if (users[i].country === 'ITALY' &&
users[i].hasDriverLicence &&
users[i].age >= 18) {
for (let j = 0; j < users[i].cars.length; j++) {
kmOfItalianDrivers += users[i].cars[j].km;
}
}
}
return kmOfItalianDrivers;
Why humans prefer
functional programming
- It focuses on what you want to achieve
- Fewer lines of code
- It encourages code reusability (composing map, flatMap, filter, reduce etc.)
- It hides implementation details
Why machines prefer
imperative programming
- It focuses on how you want to achieve it
- You write what the machine should do
- Better performance (not always)
When you write code
remember:
- Someone will review it
- Someone should be able to understand it
- Someone will take inspiration from that
- Someone will build on top of it
Hardware is cheap,
developers are expensive
-
It's better to save hours spent by developers
instead of milliseconds spent by machines
- You should help your team building things quickly
So write human-friendly code
- Functional programming can help you
- Your code will be easier to understand and easier to change
- Your colleagues will appreciate!