Daily tip #17
Tip of the day #17
Stop imposing and start to declare your code. Declarative expressions are key to parallelism, so you need to learn this path.
“This is the way”
Declarative vs Imperative Programming
Imperative Programming is HOW the program does, step by step, sequence of commands.
Look at this piece of code (thanks to Russel Winder) :
List<Integer> squareImperative(final List<Integer> datum) {
var result = new ArrayList<Integer>();
for (var i = 0; i < datum.size(); i++) {
result.add(i, datum.get(i) * datum.get(i));
}
return result;
}
Declarative Programming is WHAT the program does, the expression, without explicitly specifying its control flow.
The same result before, but using parallelStream:
List<Integer> squareDeclarative(final List<Integer> datum) {
return datum.parallelStream()
.map(i -> i * i)
.collect(Collectors.toList());
}
Venkat Subramaniam has a book called “Functional Programming in Java” where he mentions the benefits of declarative programming:
- Nicely composed, not cluttered
- Free of low-level operations
- Easier to enhance or change the logic
- Iteration controlled by a library of methods
- Efficient; lazy evaluation of loops
- Easier to parallelize where desired
Cool right? =D
How to use it
This video is the best source to start it
Refactoring from Imperative to Functional Style with Venkat Subramaniam https://www.youtube.com/watch?v=TG67kq7WUEo