liveBook · Manning

Mathematical function

As explained in Unit Testing Principles, Practices, and Patterns

A mathematical function is a computation that maps each input to exactly one output without hidden inputs or outputs and produces the same output for a given input.

A mathematical function maps each input to exactly one output, with every input and output expressed in its method signature. It produces the same output for a given input on every call. Hidden inputs include internal or external state; hidden outputs include side effects and exceptions. section 6.3 section 6.6

Explicit versus hidden state

Increment(int x) returns x + 1, so its input and output are visible and predictable. An Increment() method that reads and updates an internal x has a hidden input and changes its result across calls. CalculateDiscount(Product[] products) similarly exposes its product input and decimal output. section 6.3

public decimal CalculateDiscount(Product[] products)
{
    decimal discount = products.Length * 0.01m;
    return Math.Min(discount, 0.2m);
}

CalculateDiscount demonstrates a mathematical function whose product input and discount output are explicit. section 6.3

Explicit inputs and outputs make mathematical functions highly testable because output-based tests remain short, simple, understandable, and maintainable. Functional architecture concentrates such decision-making in a functional core while a mutable shell supplies data and applies side effects. section 6.3 section 6.6

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Defines purity, hidden inputs, and hidden outputs with code examples, but stops short of a deep functional-programming treatment.
Examples
Uses f(x) = x + 1, CalculateDiscount, deterministic Increment, stateful Increment, and AddComment to contrast explicit and hidden behavior.
What it assumes
Assumes basic methods, signatures, inputs, outputs, and unit testing while defining mathematical functions from first principles.
What you can do after
Evaluate code for hidden inputs and outputs and design highly testable logic around explicit inputs and outputs.
How it connects
Connects mathematical functions to functional programming, output-based testing, side effects, functional architecture, and hexagonal architecture.

Also explained in

Compare how 2 books explain mathematical function →

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.