# Builders the Modern Way: Named Arguments and Records

A builder fixes a long constructor, but it's a second class that repeats every field; named and optional arguments, records with with, Python dataclasses and JavaScript object literals do most of its job in the language itself, and this lesson shows when they do and when a builder still earns its place.

Journeyman · OOP · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Replace a builder with named and optional arguments, object literals or records where the language has them
- Decide when a builder still earns its place in a language with named arguments

## Key takeaways

- Named and optional arguments let a call say each value by name and leave out the rest, with no second class.
- A record (or a frozen dataclass, or a frozen object) can't be changed after it's made; with, replace or spread makes a copy with one change.
- Java has no named arguments, so Java code keeps a builder, or small with methods on a record.
- A builder still earns its place when an object is put together over time, or when rules across several parts must be checked once.

**Before this:** *Builder: Step by Step, Then Build*.

In the last lesson, a builder fixed Sam's swapped extras: every value has a name, and you call only the steps you need. It cost something, though. `ShipmentBuilder` is a whole second class that repeats every field of `Shipment`, and when the "fragile" sticker arrives, both classes change. Then Sam calls back: "Can you add a signature?" His shipment is already built, and nothing can change it. Most of today's languages have features for exactly these two jobs, and this lesson shows them.

## The symptom: a second class for every field

Put `Shipment` and `ShipmentBuilder` side by side and they're the same list twice: nine fields in one, nine fields and nine steps in the other. That's a lot of code whose only job is to let a call **name** its values and **skip** the ones it doesn't need. And a finished shipment has no way to say "the same as this one, with a signature".

- **The symptom:** a builder class that's a copy of its object's fields, kept in step by hand, and no way to make "the same, with one change".
- **The cause:** the language can't name an argument or leave one out, so a class was written to do it.

## What would you try?

**Have a tool write the builder.** Java teams often do (a code generator writes it from the class). It saves typing, but the second class is still there to read.

**Make the fields changeable, so Sam's signature is `sam.signature = true`.** That's one line, but now any code can change any shipment at any time, even after it's been priced and labeled.

**Ask the language.** If a call can name its arguments and skip the ones with defaults, the builder's main job is done for it.

## The fix: let the language name the parts

A paper shipping form works this way. Every box has a label, so you write each value next to its name, in any order. You leave a box blank when you don't need it, and the form says what blank means: "standard carrier", "no insurance".

![A paper shipping form with a labeled box for each part: Package 43, To Sam, Address Pine Rd, Carrier EcoFreight, Weight 2, Insurance checked and Pickup morning are filled in; Signature and Gift wrap are left blank, and a note says "Blank means no"](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/1d4c265fe2cc40ecbe060f01a53e9723.webp)

Here is the same shipment in each language's own way. The second part is a **record**, or something like it: an object whose values can't change once it's made (an *immutable* object). To add Sam's signature, you don't change his shipment; you make a copy with one value different.

```csharp
Shipment maya = new Shipment(42, "Maya", "Oak Ave", Carrier: "QuickShip", Pounds: 5, Insurance: true, GiftWrap: true);
Shipment sam = new Shipment(43, "Sam", "Pine Rd", Carrier: "EcoFreight", Pounds: 2, Insurance: true, PickupWindow: "morning");
// Sam calls back: add a signature. A copy, with one change.
Shipment samSigned = sam with { Signature = true };
Console.WriteLine(maya.Describe());
Console.WriteLine(sam.Describe());
Console.WriteLine(samSigned.Describe());

// Named, optional arguments, and a record whose values can't change.
record Shipment(int Id, string Recipient, string Address, string Carrier = "QuickShip", int Pounds = 1,
                bool Insurance = false, bool Signature = false, string? PickupWindow = null, bool GiftWrap = false)
{
    public string Describe()
    {
        List<string> extras = new List<string>();
        int cost = 0;
        if (Insurance) { extras.Add("insurance"); cost += 3; }
        if (Signature) { extras.Add("signature required"); cost += 2; }
        if (PickupWindow != null) { extras.Add(PickupWindow + " pickup"); }
        if (GiftWrap) { extras.Add("gift wrap"); cost += 4; }
        return $"Package {Id}, {Pounds} lb, to {Recipient} at {Address} by {Carrier}: {string.Join(", ", extras)} (${cost} extra)";
    }
}
```

```text
Package 42, 5 lb, to Maya at Oak Ave by QuickShip: insurance, gift wrap ($7 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: insurance, morning pickup ($3 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: insurance, signature required, morning pickup ($5 extra)
```

```java
// Java has no named arguments: a record, and small methods that each return a copy with one change.
record Shipment(int id, String recipient, String address, String carrier, int pounds,
                boolean insurance, boolean signature, String pickupWindow, boolean giftWrap) {
    static Shipment to(int id, String recipient, String address) {
        return new Shipment(id, recipient, address, "QuickShip", 1, false, false, null, false);
    }

    Shipment by(String carrier) { return new Shipment(id, recipient, address, carrier, pounds, insurance, signature, pickupWindow, giftWrap); }
    Shipment weighing(int pounds) { return new Shipment(id, recipient, address, carrier, pounds, insurance, signature, pickupWindow, giftWrap); }
    Shipment withInsurance() { return new Shipment(id, recipient, address, carrier, pounds, true, signature, pickupWindow, giftWrap); }
    Shipment withSignature() { return new Shipment(id, recipient, address, carrier, pounds, insurance, true, pickupWindow, giftWrap); }
    Shipment pickUpIn(String window) { return new Shipment(id, recipient, address, carrier, pounds, insurance, signature, window, giftWrap); }
    Shipment withGiftWrap() { return new Shipment(id, recipient, address, carrier, pounds, insurance, signature, pickupWindow, true); }

    String describe() {
        List<String> extras = new ArrayList<>();
        int cost = 0;
        if (insurance) { extras.add("insurance"); cost += 3; }
        if (signature) { extras.add("signature required"); cost += 2; }
        if (pickupWindow != null) { extras.add(pickupWindow + " pickup"); }
        if (giftWrap) { extras.add("gift wrap"); cost += 4; }
        return "Package " + id + ", " + pounds + " lb, to " + recipient + " at " + address + " by " + carrier + ": "
            + String.join(", ", extras) + " ($" + cost + " extra)";
    }
}

void main() {
    Shipment maya = Shipment.to(42, "Maya", "Oak Ave").by("QuickShip").weighing(5).withInsurance().withGiftWrap();
    Shipment sam = Shipment.to(43, "Sam", "Pine Rd").by("EcoFreight").weighing(2).withInsurance().pickUpIn("morning");
    // Sam calls back: add a signature. A copy, with one change.
    Shipment samSigned = sam.withSignature();
    IO.println(maya.describe());
    IO.println(sam.describe());
    IO.println(samSigned.describe());
}
```

```text
Package 42, 5 lb, to Maya at Oak Ave by QuickShip: insurance, gift wrap ($7 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: insurance, morning pickup ($3 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: insurance, signature required, morning pickup ($5 extra)
```

```python
from dataclasses import dataclass, replace


# Keyword arguments with defaults, and a dataclass whose values can't change (frozen).
@dataclass(frozen=True)
class Shipment:
    package_id: int
    recipient: str
    address: str
    carrier: str = "QuickShip"
    pounds: int = 1
    insurance: bool = False
    signature: bool = False
    pickup_window: str | None = None
    gift_wrap: bool = False

    def describe(self):
        extras, cost = [], 0
        if self.insurance:
            extras.append("insurance")
            cost += 3
        if self.signature:
            extras.append("signature required")
            cost += 2
        if self.pickup_window is not None:
            extras.append(self.pickup_window + " pickup")
        if self.gift_wrap:
            extras.append("gift wrap")
            cost += 4
        return (f"Package {self.package_id}, {self.pounds} lb, to {self.recipient} at {self.address} "
                f"by {self.carrier}: {', '.join(extras)} (${cost} extra)")


maya = Shipment(42, "Maya", "Oak Ave", carrier="QuickShip", pounds=5, insurance=True, gift_wrap=True)
sam = Shipment(43, "Sam", "Pine Rd", carrier="EcoFreight", pounds=2, insurance=True, pickup_window="morning")
# Sam calls back: add a signature. A copy, with one change.
sam_signed = replace(sam, signature=True)
print(maya.describe())
print(sam.describe())
print(sam_signed.describe())
```

```text
Package 42, 5 lb, to Maya at Oak Ave by QuickShip: insurance, gift wrap ($7 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: insurance, morning pickup ($3 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: insurance, signature required, morning pickup ($5 extra)
```

```javascript
// One object of named options, with defaults for the ones left out; frozen, so it can't change.
class Shipment {
  constructor({ id, recipient, address, carrier = "QuickShip", pounds = 1,
                insurance = false, signature = false, pickupWindow = null, giftWrap = false }) {
    Object.assign(this, { id, recipient, address, carrier, pounds, insurance, signature, pickupWindow, giftWrap });
    Object.freeze(this);
  }

  describe() {
    const extras = [];
    let cost = 0;
    if (this.insurance) { extras.push("insurance"); cost += 3; }
    if (this.signature) { extras.push("signature required"); cost += 2; }
    if (this.pickupWindow !== null) { extras.push(`${this.pickupWindow} pickup`); }
    if (this.giftWrap) { extras.push("gift wrap"); cost += 4; }
    return `Package ${this.id}, ${this.pounds} lb, to ${this.recipient} at ${this.address} by ${this.carrier}: ${extras.join(", ")} ($${cost} extra)`;
  }
}

const maya = new Shipment({ id: 42, recipient: "Maya", address: "Oak Ave", carrier: "QuickShip", pounds: 5, insurance: true, giftWrap: true });
const sam = new Shipment({ id: 43, recipient: "Sam", address: "Pine Rd", carrier: "EcoFreight", pounds: 2, insurance: true, pickupWindow: "morning" });
// Sam calls back: add a signature. A copy, with one change.
const samSigned = new Shipment({ ...sam, signature: true });
console.log(maya.describe());
console.log(sam.describe());
console.log(samSigned.describe());
```

```text
Package 42, 5 lb, to Maya at Oak Ave by QuickShip: insurance, gift wrap ($7 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: insurance, morning pickup ($3 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: insurance, signature required, morning pickup ($5 extra)
```

```typescript
// One object of named options; the ones marked ? can be left out.
interface ShipmentOptions {
  id: number;
  recipient: string;
  address: string;
  carrier?: string;
  pounds?: number;
  insurance?: boolean;
  signature?: boolean;
  pickupWindow?: string | null;
  giftWrap?: boolean;
}

class Shipment {
  readonly id: number;
  readonly recipient: string;
  readonly address: string;
  readonly carrier: string;
  readonly pounds: number;
  readonly insurance: boolean;
  readonly signature: boolean;
  readonly pickupWindow: string | null;
  readonly giftWrap: boolean;

  constructor({ id, recipient, address, carrier = "QuickShip", pounds = 1,
                insurance = false, signature = false, pickupWindow = null, giftWrap = false }: ShipmentOptions) {
    this.id = id;
    this.recipient = recipient;
    this.address = address;
    this.carrier = carrier;
    this.pounds = pounds;
    this.insurance = insurance;
    this.signature = signature;
    this.pickupWindow = pickupWindow;
    this.giftWrap = giftWrap;
  }

  describe(): string {
    const extras: string[] = [];
    let cost = 0;
    if (this.insurance) { extras.push("insurance"); cost += 3; }
    if (this.signature) { extras.push("signature required"); cost += 2; }
    if (this.pickupWindow !== null) { extras.push(`${this.pickupWindow} pickup`); }
    if (this.giftWrap) { extras.push("gift wrap"); cost += 4; }
    return `Package ${this.id}, ${this.pounds} lb, to ${this.recipient} at ${this.address} by ${this.carrier}: ${extras.join(", ")} ($${cost} extra)`;
  }
}

const maya = new Shipment({ id: 42, recipient: "Maya", address: "Oak Ave", carrier: "QuickShip", pounds: 5, insurance: true, giftWrap: true });
const sam = new Shipment({ id: 43, recipient: "Sam", address: "Pine Rd", carrier: "EcoFreight", pounds: 2, insurance: true, pickupWindow: "morning" });
// Sam calls back: add a signature. A copy, with one change.
const samSigned = new Shipment({ ...sam, signature: true });
console.log(maya.describe());
console.log(sam.describe());
console.log(samSigned.describe());
```

```text
Package 42, 5 lb, to Maya at Oak Ave by QuickShip: insurance, gift wrap ($7 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: insurance, morning pickup ($3 extra)
Package 43, 2 lb, to Sam at Pine Rd by EcoFreight: insurance, signature required, morning pickup ($5 extra)
```

The first two lines are the builder lesson's, and `ShipmentBuilder` is gone. Each call names its values (`Insurance: true`, `insurance=True`, `insurance: true`) and leaves out the rest, which take their defaults. The "fragile" sticker is one new field with a default, in one class. And Sam's signature is a copy: his first shipment is still there, unchanged, for the label that was already printed.

**Where the languages differ.**

- **C#:** named arguments (`Pounds: 5`) and optional ones (`= false`) work on any method; a `record` can't be changed after it's made, and `with { ... }` makes a copy with some values changed.
- **Python:** every function takes keyword arguments; `@dataclass(frozen=True)` writes the constructor and makes the object unchangeable, and `dataclasses.replace` makes the copy.
- **JavaScript and TypeScript:** no named arguments, so the call hands in one object of named options, with defaults for the ones left out; `{ ...sam, signature: true }` (the *spread*) copies Sam's values and changes one. TypeScript's `?` marks which options can be left out, and `readonly` stops anything changing them later.
- **Java:** no named arguments at all. A record holds the values and can't be changed, so each step is a small method that returns a copy with one value different. The other common choice is to keep the builder class from the last lesson.

## When a builder still earns its place

Named arguments do the builder's main job. A builder is still worth its second class when:

- **The object is put together over time.** A checkout screen that asks for the extras one page at a time can hold a builder and fill it in as the customer goes, then build once at the end. A constructor needs everything at once.
- **Rules cross several parts, and must be checked once.** "SameDay only goes to zones 1 and 2" is about the carrier *and* the address. A builder's `build` step checks them together before the shipment exists.
- **Your language has no named arguments.** In Java, the builder (or the copy methods above) is still the readable way.
- **The same steps make different things.** A label and a customs form built from the same steps is the original book's version of the pattern.

| | A builder class | Named and optional arguments |
|---|---|---|
| **Reads best when** | the object is made in steps, or the language can't name arguments | the object is made in one call |
| **Adding a field** | a field and a step in the builder, and a field in the object | one field with a default |
| **Checking rules** | once, in `build` | in the constructor, or not at all |
| **Watch out for** | a builder that drifts out of step with its object | a call with so many named values it's still hard to read |

## How it got its name

None of this is a new pattern. It's the **Builder pattern's** job done by the language: the named arguments are the named steps, and the defaults are the steps you skip. Records, frozen dataclasses and frozen objects are **immutable objects**, and making "a copy, with one change" leads straight to the next lesson.

## Where you've already used it

- Python's `print("Done", end="")` and `sorted(packages, reverse=True)`: keyword arguments with defaults.
- JavaScript's `fetch(url, { method: "POST", headers: ... })`: one object of named options.
- C#'s `new HttpClient { Timeout = TimeSpan.FromSeconds(10) }`: an object initializer, which names the values you set.

## When not to use it

- **When every value is needed and there are two or three.** `new Box(5)` is clearer than `new Box(pounds: 5)`.
- **When the defaults hide a decision.** If a missing carrier should be a mistake, don't give it a default; make it required.

**How often you'll meet it:** every day (our estimate: named arguments, option objects and records are everywhere in modern code).

## Check yourself

2 questions to try on the lesson page.

## So what

Before writing a builder, ask whether your language can name the parts already. Most can, and then the builder's only remaining jobs are objects made over time, rules that cross several parts, and languages like Java.

## Key terms

- [Builder Pattern](https://www.ask-codey.com/glossary/builder-pattern)
- [Immutable Object](https://www.ask-codey.com/glossary/immutable-object)
- [Long Parameter List](https://www.ask-codey.com/glossary/long-parameter-list)

## Cheat sheets

- [Builders the Modern Way: Named Arguments and Records](https://www.ask-codey.com/cheat-sheets/dp-builder-modern-cheat-sheet)

Source: https://www.ask-codey.com/lessons/dp-builder-modern
