generated from skills/github-pages
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #20 from brunobaiano/tip-17
tip-17
- Loading branch information
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
--- | ||
title: "Daily tip #17" | ||
date: 2023-11-15 | ||
--- | ||
|
||
## 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) : | ||
|
||
|
||
```java | ||
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: | ||
|
||
|
||
```java | ||
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 |