Functional compositioneasy0-2 years

`Function<Integer, Integer> plus2 = x -> x + 2;` and `times3 = x -> x * 3;`. `plus2.andThen(times3).apply(5)` returns 21 and `plus2.compose(times3).apply(5)` returns 17 — same two functions, different answers. What's the rule, and which should application code default to?

andThen runs the function it's called on first, then the argument — plus2.andThen(times3) means "do plus2, and then do times3", which reads left to right exactly the way the code is written: (5 + 2) × 3 = 21. compose runs the argument first, then the function it's called on — plus2.compose(times3) means "do times3, then plug that into plus2", right to left, the way mathematicians write f ∘ g: (5 × 3) + 2 = 17. Both methods exist and both are correct; the trap is assuming they read the same direction because they're written the same way, chained onto the same receiver. andThen matches reading order and is the one to default to in application code — reach for compose only when you deliberately mean "apply this argument's function before the one I'm calling it on", and want the code to say so.

The lesson behind it →