Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ change that a consumer must act on has a "Consumer action:" line.
checks only the local links and skips each dkstack URL. With it, the run checks each dkstack file and
anchor against a clone of the dkstack branch. The run in dkstack does not change. `setup-quality-gates`
copies the script and documents both forms.
- `coding/immutability.md` (#364). Declare a variable so that it cannot be reassigned, do not change an argument, and make value objects immutable. A change in place needs a measurement and stays inside one function or type.
- `scripts/check-diagrams.mjs` (#316). It checks the format rules of `make-diagram`. A `mermaid`
block with no paragraph directly above it fails. A tracked `.png` or `.svg` file in `docs/`
fails. A diagram with more than 12 nodes gives a warning only. `npm run check` and `validate`
Expand Down
49 changes: 49 additions & 0 deletions coding/immutability.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Immutability

Make a value unchangeable by default. Change a value only when the change is the purpose of the
code.

Apply this page to code that you add or change.

## Rules

- Declare a variable so that it cannot be reassigned, for example with `const`, `readonly`,
`final` or `val`. Use a variable that can be reassigned only when its value must change.
Reason: the reader knows that the value stays the same after the declaration.
- Do not change an argument that the caller gives you. Return a new value. Reason: the caller
does not expect that its value changes.
- Make a value object and a data transfer type immutable. Use readonly fields, a C# `record`
with `init` properties, a Java `record` or a Python `@dataclass(frozen=True)`. A C# `record`
with `set` properties is not immutable. Reason: an immutable value
is safe to share, to cache and to use as a key.
- A declaration that cannot be reassigned does not make the value immutable. In JavaScript,
`const user = { name: "A" }` still lets code change `user.name`. Use `Readonly<T>`,
`readonly` arrays or `Object.freeze` when the content must not change. These are shallow. A
nested object or array can still change, so apply the same type or call to each level.
- Do not share changeable state between threads or actors without an owner. See
[architecture/concurrency.md](../architecture/concurrency.md).
- A copy can be too slow, for example in a hot loop over a large array. Change the value in place
only when a measurement shows the cost. Keep the change inside one function or one type. Do not
let the changeable value leave it. See [performance testing](../tdd/performance-testing.md).

## Enforcement

Prefer native checks and run them in CI as errors. Examples are ESLint `prefer-const` and
`no-param-reassign` with `props: true`, typescript-eslint `prefer-readonly`, and the
`readonly` modifier and `init` accessors in C#. Review the rules that no tool checks reliably,
for example a change to an argument through a method call.

## Good example

`applyDiscount(order: DeepReadonly<Order>, percent: number): Order` returns a new order with new
line totals. `DeepReadonly` is a type that makes each nested field readonly. It comes from a
library or from the project. It stops a change to `order.lines[0].total`. The caller keeps the old
order for the audit log.

## Bad example

`applyDiscount(order, percent)` changes `order.lines` in place and returns nothing. The audit log
keeps a reference to the same order. It now shows the discounted totals as the original totals.

Related: [design by contract](../architecture/design-by-contract.md),
[orthogonality](../architecture/orthogonality.md).
1 change: 1 addition & 0 deletions coding/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Coding standards and practices.
- [brace-style.md](brace-style.md): Brace placement and formatter exceptions.
- [practices.md](practices.md): Development practices.
- [quality.md](quality.md): Code quality rules.
- [immutability.md](immutability.md): Make values unchangeable by default.
- [naming.md](naming.md): Identifier forms, meaning and enforcement.
- [types.md](types.md): No escape from the type system, and explicit types.
- [quality-gates.md](quality-gates.md): Never weaken a quality gate.
Expand Down
48 changes: 48 additions & 0 deletions test/immutability.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { readFile } from "./helpers.mjs";

const root = join(dirname(fileURLToPath(import.meta.url)), "..");

async function text(path) {
return readFile(join(root, path), "utf8");
}

test("coding/immutability.md states the immutability rules", async () => {
const page = await text("coding/immutability.md");
for (const part of [
"# Immutability",
"`const`",
"`readonly`",
"`final`",
"`val`",
"argument",
"Return a new value",
"value object",
"measurement",
"prefer-const",
"no-param-reassign",
"architecture/concurrency.md",
"Object.freeze",
"`no-param-reassign` with `props: true`",
"`prefer-readonly`",
"`init`",
"`@dataclass(frozen=True)`",
"These are shallow",
"DeepReadonly` is a type that makes each nested field readonly",
]) {
assert.ok(page.includes(part), `missing ${part}`);
}
});

test("coding/immutability.md has a good and a bad example", async () => {
const page = await text("coding/immutability.md");
assert.ok(page.includes("## Good example"), "missing good example");
assert.ok(page.includes("## Bad example"), "missing bad example");
});

test("coding/index.md lists coding/immutability.md", async () => {
assert.ok((await text("coding/index.md")).includes("(immutability.md)"), "coding/index.md does not list the page");
});