liveBook · Manning

Referential transparency

As explained in Unit Testing Principles, Practices, and Patterns

Referential transparency is the property that a method call can be replaced by its return value without changing program behavior.

Referential transparency means replacing a method call with its return value without changing program behavior. It indicates that the method's observable output is fully represented by its inputs and return value. section 6.3

A method loses referential transparency when it reads hidden inputs or produces hidden outputs. Current time, database queries, private mutable fields, and mutations such as adding to a collection can make an apparently simple method behave unlike a mathematical function. section 6.3

Use the principle to distinguish transparent functions from methods with side effects:

  • CalculateDiscount(products) is transparent because its product input and decimal result are explicit. section 6.3
  • Increment(4) can be replaced with 5; an Increment method that changes internal state cannot. section 6.3
  • AddComment returns a Comment but also mutates a collection, creating a hidden output. section 6.3
public decimal CalculateDiscount(Product[] products)
{
    decimal discount = products.Length * 0.01m;
    return Math.Min(discount, 0.2m);
}

Inspect a transparent calculation whose input and output are explicit in the method signature. section 6.3

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Defines replacement equivalence, exposes hidden inputs and outputs, and contrasts pure calculations with state mutation.
Examples
Uses CalculateDiscount, Increment, DateTime.Now, database queries, and AddComment to expose explicit and hidden behavior.
What it assumes
Assumes familiarity with methods and return values while introducing mathematical functions, hidden inputs, and side effects.
What you can do after
Evaluate whether a method's return value captures all relevant behavior and locate hidden state or side effects.
How it connects
Connects mathematical functions and side effects to functional architecture and hexagonal architecture.

Also explained in

Compare how 9 books explain referential transparency →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.