Composing functions

A function that is built out of named functions is easier to read, test and change than the same work written as one method with four steps inside it. The two tools are andThen, which chains functions, and the and, or and negate of a predicate. This lesson uses them for the two jobs they fit: a set of validation rules and a text transformation.

Rules as a list of predicates

A rule is a name, a predicate and the message it produces when the predicate fails. Kept in a list, the rules are data: the checker is one loop, and a new rule is one line that nobody has to thread through a method:

import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; public class Validation { record Rule(String name, Predicate<String> test, String message) { } public static void main(String[] args) { List<Rule> rules = List.of( new Rule("not empty", s -> !s.isEmpty(), "value is empty"), new Rule("at least 3", s -> s.length() >= 3, "value is too short"), new Rule("no spaces", s -> !s.contains(" "), "value has a space"), new Rule("lower case", s -> s.equals(s.toLowerCase()), "value is not lower case")); for (String value : List.of("good", "x", "two words", "UPPER", "fine")) { System.out.println(value + " -> " + check(value, rules)); } } static List<String> check(String value, List<Rule> rules) { List<String> failures = new ArrayList<>(); for (Rule rule : rules) { if (!rule.test().test(value)) { failures.add(rule.message()); } } return failures; } }

javac -Xlint:all Validation.java
java Validation

good -> []
x -> [value is too short]
two words -> [value has a space]
UPPER -> [value is not lower case]
fine -> []

The empty list is the success case, which a caller reads with isEmpty. The three failures name the rule that failed and not the class of an exception, and a value can collect several at once, because the loop does not stop at the first. That is the difference between this shape and a method that throws: a form wants every problem in one pass, a parser wants the first one.

A function built from steps

A slug is a title with the spaces turned into dashes and the case lowered. Each step is one small function with a name, and the slug is four of them chained:

import java.util.function.Function; public class Pipeline { static final Function<String, String> STRIP = String::strip; static final Function<String, String> LOWER = String::toLowerCase; static final Function<String, String> COLLAPSE = s -> s.replaceAll(" +", " "); static final Function<String, String> DASHES = s -> s.replace(' ', '-'); public static void main(String[] args) { Function<String, String> slug = STRIP.andThen(LOWER).andThen(COLLAPSE).andThen(DASHES); for (String title : new String[] {" Hello World ", "Java Streams", "A B C"}) { System.out.println("[" + title + "] -> " + slug.apply(title)); } Function<String, String> trimmedLower = STRIP.andThen(LOWER); System.out.println(trimmedLower.apply(" Mixed Case ")); System.out.println(LOWER.compose(STRIP).andThen(DASHES).apply(" Two Words ")); } }

javac -Xlint:all Pipeline.java
java Pipeline

[ Hello World ] -> hello-world
[Java Streams] -> java-streams
[A B C] -> a-b-c
[ Mixed Case ] -> mixed case
[ Two Words ] -> two-words

The name of each step is the whole documentation of it, and the chain reads in the order the text goes through it. trimmedLower is the same two steps reused for another job, which is the reason to name them. LOWER.compose(STRIP) is the same as STRIP.andThen(LOWER), written from the other end; lesson 083 showed the two orders on a pair of functions.

A validator from parts

A form check combines both tools: a cleaning function applied to every value, and two predicates, one of which applies only to one field. The problems are collected as records, so the caller can print them or count them:

import java.util.ArrayList; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; public class Form { record Field(String name, String value) { } record Problem(String field, String message) { } public static void main(String[] args) { List<Field> fields = List.of( new Field("name", " Ada "), new Field("email", "ada.example"), new Field("age", "36")); Predicate<String> notBlank = v -> !v.isBlank(); Predicate<String> hasAt = v -> v.contains("@"); Function<String, String> clean = v -> v.strip().toLowerCase(); List<Problem> problems = new ArrayList<>(); for (Field field : fields) { String value = clean.apply(field.value()); if (!notBlank.test(value)) { problems.add(new Problem(field.name(), "is blank")); } else if (field.name().equals("email") && !hasAt.test(value)) { problems.add(new Problem(field.name(), "has no @")); } } System.out.println(problems); System.out.println(problems.isEmpty() ? "accepted" : "rejected: " + problems.size()); } }

javac -Xlint:all Form.java
java Form

[Problem[field=email, message=has no @]]
rejected: 1

The cleaning step is applied once per field and the checks read the cleaned value, so the validation and the value that reaches the next stage cannot disagree. The email rule is not a general rule, and that is why it is written where it is: the list-of-rules shape of the first program is for rules every value shares, and a field-specific rule belongs beside the field.

What composition buys

Three things, and they are the reason the functional part of the course exists. Each piece has a name, so a failure message or a log line can name it, and the test of a rule is the test of a small function. The pieces can be reused in another order for another job, as trimmedLower does. And the assembled function is a value: it can be passed, stored in a field, put in a list, and given a different implementation by a caller, which is what lesson 062 calls composition.

The cost is indirection: a reader who wants the whole behaviour has to follow the chain, and a debugger steps through each link. The trade is worth it when the pieces are real, which is why the lesson has three steps in a slug and four rules in a validator, and not one function per line of a method.

Exercises

  1. Add a rule to Validation that rejects a value longer than eight characters and run the program.
  2. Add a step to the slug that removes a trailing dash and print the three titles again.
  3. Give Form a second field-specific rule, for a name of at least two letters.
  4. Write a function that returns a function, and use andThen on the result of two calls.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does f.andThen(g) produce?

    Answer

    A function that applies f and then g to the result

    The chain returns a new function, and the second step reads the output of the first.

  2. Why is a list of rules better than one method with four checks?

    Answer

    A rule is data: it can be added, printed, named in a message and tested alone

    The loop over the list is the only code that changes when a rule is added.

  3. What does a validation that returns a list of problems do that a throwing method cannot?

    Answer

    It reports every failure in one pass

    A form wants all the problems at once, while an exception stops at the first.

  4. What does this program print? import java.util.function.Function; public class Q1 { public static void main(String[] args) { Function<Integer, Integer> plus = n -> n + 1; Function<Integer, Integer> times = n -> n * 3; System.out.println(plus.andThen(times).apply(2)); System.out.println(times.andThen(plus).apply(2)); } }

    Answer

    9 / 7

    Adding then tripling gives nine, and tripling then adding gives seven.

  5. What does this program print? import java.util.function.Predicate; public class Q2 { public static void main(String[] args) { Predicate<String> a = s -> s.startsWith("x"); Predicate<String> b = s -> s.length() > 2; System.out.println(a.or(b).test("xy")); System.out.println(a.and(b).test("xy")); } }

    Answer

    true / false

    xy starts with x but has only two letters, so or holds and and does not.

  6. What is a Function<String, String> stored in a field good for?

    Answer

    It can be reused, passed and combined by any caller

    A function as a value is the point of the functional interfaces, and reuse is what composition builds on.

  7. What does negate do to a predicate?

    Answer

    Returns the opposite predicate

    negate gives a new predicate that answers the other way, which reads better than a ! inside a lambda.

  8. What does this program print? import java.util.function.Function; public class Q3 { public static void main(String[] args) { Function<String, String> upper = String::toUpperCase; Function<String, Integer> length = String::length; System.out.println(upper.andThen(length).apply("abc")); } }

    Answer

    3

    The upper case is applied first and has no effect on the length of three.

  9. Why does a chain of named steps beat one long method?

    Answer

    Each step can be tested, named in a log and reused elsewhere

    The pieces are the units of test and documentation, and the chain is their assembly.

  10. What does this program print? import java.util.function.Predicate; public class Q4 { public static void main(String[] args) { Predicate<Integer> positive = n -> n > 0; System.out.println(positive.negate().test(5)); System.out.println(positive.and(n -> n < 10).test(5)); } }

    Answer

    false / true

    Five is positive and below ten, so the negation is false and the conjunction true.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev