liveBook · Manning

Pure function

As explained in 100 Java Mistakes and How to Avoid Them

A stateless function computes each result without depending on mutable state or other invocations of the function.

A pure function computes each result from its inputs without retaining state between invocations. Stream API functions used by map() must be stateless; relying on encounter order or a previous element violates that contract. section 9.5

A stateful adjacent-element mapper

This pairMap implementation stores prev and started inside a Function, then maps and skips the first result. It may appear to work sequentially, but parallel execution can invoke the function in an order the stored state cannot safely represent. section 9.5

Avoid the mistake by:

  • Following the Stream API contract even when callers control later operations. section 9.5
  • Testing stream-consuming or stream-producing utilities after applying parallel(). section 9.5
  • Using StreamEx for pairwise mapping when a dependency is acceptable, or avoiding Stream API for problems it cannot express idiomatically. section 9.5

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains state retention, encounter-order assumptions, and parallel failure, but stops short of implementing a general pairwise operation.
Examples
Uses a pairMap utility that combines adjacent strings and a stateful Function storing the previous element.
What it assumes
Assumes familiarity with Java streams, map(), parallel(), sequential(), Function, and BiFunction.
What you can do after
Diagnose stateful stream operations, test utilities with parallel(), and choose StreamEx or a non-Stream solution when appropriate.
How it connects
Connects pure functions with Stream API, map(), sequential streams, parallel streams, and utility-method design.

Also explained in

Compare how 19 books explain pure function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.