Overview

11 Representing state and change

This chapter introduces a functional view of change: rather than thinking of an object as something whose internal state is updated over time, it encourages treating each observed state as a separate snapshot. That shift matters because mutable shared state is a major source of bugs, especially in concurrent programs, where race conditions can lose updates, violate invariants, and create hard-to-reproduce failures. The chapter also notes that even when mutation is encapsulated inside a class, it can still behave like global mutable state by coupling many parts of a system to the same object and by introducing side effects that break purity.

To avoid these problems, the text shows how to represent change without mutation by creating new instances instead of modifying existing ones. It uses immutable values, records, and with expressions to model evolving entities such as product inventory and bank accounts, while preserving previous versions of data when needed. The chapter also explains how to make immutability practical in C#: use read-only properties when a value should never change, use init-only properties when a modified copy is appropriate, and ensure that immutability extends all the way down by copying or replacing mutable collections with immutable ones. It also points out that immutable data can coexist with performance-conscious design, because copies are often shallow and the overhead is usually modest.

A central example is an account model built from immutable data objects, where the account state holds only data and separate functions perform transitions such as create, activate, and add transaction. This separation reduces coupling and makes business rules easier to reason about, test, and reuse, since the logic becomes a higher-level module operating on a lower-level data structure. The chapter ends by connecting this style to data-oriented programming, which similarly favors separating data from logic and using immutable structures, while acknowledging that more generic representations can trade type safety for flexibility.

Loss of data as a result of concurrent updates. Both threads cause the Inventory value to be updated concurrently with the result that one of the updates is lost.
In FP, change can be represented by creating new versions of the data.
An entity whose state changes over time
Representing state and logic related to an entity are separate concerns. In this example, AccountState captures the data representing an account, while Account is a collection of functions that model changes to an account.

Summary

  • FP discourages state mutation, preventing several drawbacks associated with state mutation, such as lack of thread safety, coupling, and impurity:
    • Things that don’t change are represented with immutable objects.
    • Things that change are also represented with immutable objects; these immutable snapshots represent an entity’s state at a given point. Change is represented by creating a new snapshot with the desired changes.
  • Use records to define custom immutable data types.
  • For a type to be immutable, all its children, including lists and other data structures, must also be immutable.
  • You can simplify your application and promote loose coupling by separating data from logic:
    • Use data objects (typically records) to encapsulate data.
    • Use functions (implemented as static methods within stateless static classes) to represent business logic.

FAQ

What is state mutation, and why is it a problem in functional programming?State mutation is updating memory in place. In functional programming, it is discouraged because it can create race conditions, hidden coupling between parts of the program, and side effects that make code harder to reason about and test.
Why is shared mutable state unsafe in concurrent programs?When multiple threads read and update the same mutable state at the same time, one update can overwrite another. This can lead to lost data, inconsistent values, and unpredictable behavior that is often very hard to reproduce.
What is an example of a race condition in the chapter?The chapter uses a Product class with a mutable Inventory property. If one thread replenishes inventory while another processes a sale, both may read the same old value and overwrite each other’s updates, causing one change to be lost.
Why can mutable objects temporarily violate invariants?If an object has multiple related fields, one field may be updated before the others. During that brief window, the object can appear invalid to another thread. For example, Inventory may be updated before IsLowOnInventory, breaking the invariant that low inventory must match the inventory count.
What does it mean to represent change without mutation?It means not updating values in place. Instead, you create a new instance that reflects the change, while the original value remains unchanged. This preserves earlier states and avoids the problems caused by mutation.
Why are immutable values important in functional programming?Immutable values cannot be changed after creation, so they are inherently safer to share, easier to reason about, and free from side effects caused by in-place updates. They also work well with concurrency because no thread can alter them once created.
How do records and with expressions help model state changes in C#?Records make it easy to define immutable data objects, and with expressions create modified copies of those objects. This lets you model changes such as activating an account or updating status without mutating the original instance.
Why should immutable objects avoid mutable members like List<T>?Even if the outer object is a record, it is not truly immutable if it contains a mutable collection. A separate reference to that list could still be modified, changing the supposedly immutable object indirectly. Defensive copying or immutable collections prevent this.
Why does the chapter recommend separating data and logic?Separating data from logic reduces coupling and makes systems easier to understand and maintain. In the chapter, AccountState holds the data, while a static Account class contains functions that represent state transitions like create, activate, and add transaction.
What is the difference between a value object and an entity in this chapter?A value object’s identity is fully captured by its value, like a number, date, or circle. An entity, such as a bank account, keeps the same identity over time even as its state changes, so its behavior must model transitions between snapshots of state.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Functional Programming in C#, Second Edition Functional Programming in C#, Second Edition ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Functional Programming in C#, Second Edition Functional Programming in C#, Second Edition ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Functional Programming in C#, Second Edition Functional Programming in C#, Second Edition ebook for free