Gangmax Blog

A Java Code Sample of High Order

The code below shows how to convert a code repetition into a simplified abstraction with high order function implementation. At the first glance, this might be unnecessary. However as the code lines increase, such abstractions will make the code neat and short.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import org.apache.commons.lang3.tuple.Triple;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;

public class Actions {

public static void get(String path, Function<String, String> handler) {
System.out.println("get path = " + path);
System.out.println("get handler result = " + handler.apply(path));
}

public static void post(String path, Function<String, String> handler) {
System.out.println("post path = " + path);
System.out.println("post handler result = " + handler.apply(path));
}

public static void main(String[] args) {
// The original code.
runPlainOld();
// The updated code.
List<Triple<BiConsumer<String, Function<String, String>>, String, Function<String, String>>> triples = new ArrayList<>();
triples.add(Triple.of(Actions::get, "/running", name -> name));
triples.add(Triple.of(Actions::get, "/:taskId", jobId -> "taskId=" + jobId));
triples.add(Triple.of(Actions::post, "/sayhello", name -> "Hello, " + name));
runHighOrder(triples);
}

public static void runPlainOld() {
get("/running", name -> name);
get("/:taskId", jobId -> "taskId=" + jobId);
post("/sayhello", name -> "Hello, " + name);
}
public static void runHighOrder(List<Triple<BiConsumer<String, Function<String, String>>, String, Function<String, String>>> triples) {
for (Triple<BiConsumer<String, Function<String, String>>, String, Function<String, String>> triple : triples) {
triple.getLeft().accept(triple.getMiddle(), triple.getRight());
}
}
}

Comments