liveBook · Manning

Mutable shared state

As explained in 100 Go Mistakes and How to Avoid Them

Mutable shared state is data that can be modified and is accessible by multiple parts of a program or concurrent executions.

A package-level clock such as `var now = time.Now` is mutable shared state. Tests that depend on it are coupled through the same variable and cannot safely run in parallel. section 11.6

For time-dependent cache tests, inject a `func() time.Time` into the cache and provide a fixed-time implementation. If external-package tests cannot access that dependency, let callers supply the time or cutoff; passing a cutoff is simplest and needs no stub type. section 11.6

var now = time.Now      #1

This package-level clock illustrates the shared-variable approach that can couple tests. section 11.6

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains how a global clock couples tests, then contrasts struct-level clock injection with caller-supplied timestamps.
Examples
Uses a cache that trims timestamped events, a global clock variable, and a fixed-time test dependency.
What you can do after
Apply clock injection or caller-supplied cutoffs to make time-dependent tests deterministic and isolated.
How it connects
Connects mutable globals with dependency injection, unit-test isolation, and parallel tests.

Also explained in

Compare how 2 books explain mutable shared state →

Related concepts

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