Composition and higher-order functions

Passing behaviour instead of flags, and the ordering trap: andThen gave 21 and compose gave 17 from the same two functions.

7 min read✨ Modern Java: 8 to 25

A higher-order function takes a function or returns one. Composition builds a new function out of existing ones. Together they are how the functional style replaces a long method with small pieces you can recombine — and they have one ordering trap that catches almost everyone.

Higher-order functions, which you use every day

You have been writing them since the first lambda:

java
list.sort(Comparator.comparing(Order::total));      // takes a function
orders.stream().map(Order::id)                      // takes a function
Comparator.comparing(Order::total)                  // RETURNS a function

sort, map and filter take behaviour as an argument. Comparator.comparing goes further: it takes a function and returns a new one — a comparator built from an extractor. That second kind is where composition lives.

The reason this is worth naming is that it changes what "reusing code" means. Instead of a method with a flag parameter that switches behaviour, you pass the behaviour in:

java
// a flag
List<Order> filter(List<Order> xs, boolean onlyPaid, boolean onlyLarge) { ... }
 
// behaviour
List<Order> filter(List<Order> xs, Predicate<Order> keep) { ... }
filter(orders, Order::isPaid.and(o -> o.total() > 1000));

The flag version needs a new parameter for every new rule and a combinatorial set of branches. The predicate version needs neither — which is the strategy pattern from the design patterns course, arriving from the other direction.

Composition, and the order that trips people

Function has two composition methods that read almost the same and do opposite things. Two functions, starting from 5:

java
Function<Integer, Integer> plus2  = x -> x + 2;
Function<Integer, Integer> times3 = x -> x * 3;
plaintext
###   plus2.andThen(times3).apply(5) = 21
###   plus2.compose(times3).apply(5) = 17

Same two functions, different answers:

  • andThen runs plus2 first, then times3: (5 + 2) × 3 = 21. It reads left to right, the way the code is written.
  • compose runs times3 first, then plus2: (5 × 3) + 2 = 17. It reads right to left, the way mathematics writes f ∘ g.

The rule that removes the confusion: andThen means "and then", in the order you read it. compose follows the mathematical convention and is the one to be careful with. If a chain is surprising, it is almost always a compose somebody read left to right.

Building behaviour out of pieces

The payoff is combining small, named, tested functions into larger ones without writing a new method:

java
Predicate<Order> paid    = Order::isPaid;
Predicate<Order> large   = o -> o.total() > 1000;
Predicate<Order> flagged = Order::isFlagged;
 
Predicate<Order> needsReview = paid.and(large).and(flagged.negate());

needsReview is readable as a sentence, each piece is independently testable, and changing the rule is editing one line rather than restructuring an if. Comparator does the same for ordering:

java
Comparator<Order> byPriority = comparing(Order::isUrgent).reversed()
    .thenComparing(Order::total, reverseOrder())
    .thenComparing(Order::id);

That last thenComparing(Order::id) is the pagination lesson's unique tiebreaker, written as composition.

Returning a function

A function that builds and returns a function lets you configure behaviour once and apply it many times:

java
static Function<Double, Double> applyDiscount(double percent) {
    return price -> price * (1 - percent / 100);
}
 
Function<Double, Double> festival = applyDiscount(20);
festival.apply(1000.0);    // 800.0

percent is captured when applyDiscount runs and remembered by the returned lambda. This is a closure, and it is subject to the rule the lambdas lesson covered: a captured local must be effectively final, because it is copied into the lambda rather than shared.

Where it stops paying

The functional style is a tool, and the paradigms lesson's warning applies: it is not a ranking.

  • A long chain is harder to debug than a loop. There is no line to put a breakpoint on inside a.andThen(b).andThen(c).andThen(d), and the stack trace is a list of lambda frames.
  • Point-free style can hide meaning. map(Order::total).reduce(0L, Long::sum) is clear; four composed method references with no names is a puzzle.
  • Checked exceptions do not compose. A Function cannot throw one, so a pipeline that touches I/O fills with try/catch wrappers.

The guideline that holds up: compose when each piece has a name and a meaning. When you find yourself composing anonymous pieces to avoid writing a method, write the method.

Under the hood: what a lambda compiles to

A lambda looks like it should desugar to an anonymous inner class, and for years explanations said exactly that. It does not — and the difference is not academic; it changes what shows up in a heap dump and why lambda creation is cheap.

Compile x -> x + 2 and look inside the .class file: there is no generated inner class at all. The lambda's body is emitted as a private synthetic method on the enclosing class (something like lambda$plus2$0), and the call site where you wrote the lambda becomes an invokedynamic instruction. The first time that instruction executes, the JVM resolves it through a bootstrap method — LambdaMetafactory.metafactory — which generates, at run time, a hidden implementation class that implements Function and forwards its apply to that synthetic method, using the low-level MethodHandle machinery from java.lang.invoke. That generated class is cached on the call site, so every later execution of the same lambda expression reuses it instead of paying generation cost again — the same "generate once, cache, dispatch" shape the JDK dynamic proxy uses for InvocationHandler, though the two mechanisms (invokedynamic+LambdaMetafactory vs. Proxy.newProxyInstance) are otherwise unrelated.

This is why a method reference like Order::isPaid and a lambda o -> o.isPaid() are not "syntax sugar for the same anonymous class" — there usually is no anonymous class for either. It also explains a detail that trips people reading a stack trace: a lambda's generated class has a synthetic name like Composition$$Lambda/0x00000..., not Composition$1, because it was never compiled as a nested class — it was manufactured by the metafactory the first time that call site ran.

Try it yourself

Trace a composed pipeline

java
Function<Integer, Integer> plus2  = x -> x + 2;
Function<Integer, Integer> times3 = x -> x * 3;
Function<Integer, Integer> minus4 = x -> x - 4;
 
Function<Integer, Integer> pipeline = plus2.andThen(times3).compose(minus4);
System.out.println(pipeline.apply(10));
Answer

24. compose's argument is the first thing to run, no matter how much sits to its left: f.compose(g) means x -> f.apply(g.apply(x)), and here f is the whole plus2.andThen(times3) chain — from compose's point of view that chain is just one Function value. So minus4 runs first (10 − 4 = 6), then the andThen chain runs left to right on its result (6 + 2 = 8, then 8 × 3 = 24). The trap is treating andThen and compose as if they read the same direction because they are chained on one line; each one decides its own order independently of where it sits in the expression.

Misconceptions

  • "A lambda desugars to an anonymous inner class, just like Java 7." It compiles to a private synthetic method plus an invokedynamic call site; the actual implementation class is generated at run time by LambdaMetafactory, the first time that call site executes, and cached from then on. There is no .class file for it sitting in your build output the way Composition$1.class would be.
  • "Every lambda allocates a new object on every call." Only capturing lambdas do, and only per distinct set of captured values — a non-capturing lambda's generated instance is created once per call site and reused for the life of the program.

Sources

  • JSR 335 / JEP-era lambda expressions design documents and java.lang.invoke.LambdaMetafactory Javadoc — the invokedynamic bootstrap mechanism lambdas compile to.
  • The Java Virtual Machine Specification, §6.5 (the invokedynamic instruction) and java.lang.invoke package documentation (MethodHandle, call site linkage).
  • java.util.function.Function Javadoc — the exact composition order of andThen and compose.
Progress is saved on this device and to your account when signed in.