# Prototype: Duplicate, Then Change

When "the same as last week, new address" is made by copying a shipment field by field, the copying code forgets whatever was added since; letting the shipment copy itself fixes that, as long as the copy doesn't share its list of boxes with the original, the bug that shallow and deep copies are about.

Apprentice · OOP · Updated November 17, 2026

By Gregor Dzierzon

## After this lesson you can

- Make a new object by copying an existing one and changing only what's different
- Tell a shallow copy from a deep copy, and predict the bug when a copy shares a list
- Spot the smells that point to Prototype: an object rebuilt field by field to get one that's almost the same

## Key takeaways

- The smell: outside code rebuilds an object field by field to get one that's almost the same, and misses the newest field.
- The cause: only the object knows all of its fields, but the copying is done somewhere else.
- The fix: the object copies itself; the caller duplicates it, then changes what's different.
- A shallow copy shares the lists inside it with the original; a deep copy gets its own. Change a shared list and both change.

**Before this:** *Meet the Package Tracker*, and lists inside objects.

Sam ships a box of books to his brother every week, with insurance and gift wrap. This week his brother has moved to Cedar Ln, and there's one more box. Lakeside Parcel's tracker has a **"same as last week"** button for exactly this, and it has a bug that nobody noticed for a month. This lesson ends with a pattern called *Prototype*, and with the second bug that waits for whoever fixes the first.

## The symptom: copied field by field, and one was missed

Last week's shipment has two boxes, 5 and 2 pounds. The "same as last week" screen copies each field into a new shipment, then changes the address and adds this week's 8-pound box:

```csharp
Shipment lastWeek = new Shipment("Sam", "Oak Ave", true, new List<int> { 5, 2 }, giftWrap: true);

// The "same as last week" screen: copy each field by hand, then change what's new.
Shipment thisWeek = new Shipment(lastWeek.Recipient, "Cedar Ln", lastWeek.Insurance, new List<int>(lastWeek.Boxes));
thisWeek.Boxes.Add(8);

Console.WriteLine("Last week: " + lastWeek.Describe());
Console.WriteLine("This week: " + thisWeek.Describe());

class Shipment
{
    public string Recipient { get; }
    public string Address { get; set; }
    public bool Insurance { get; }
    public List<int> Boxes { get; }
    public bool GiftWrap { get; } // added last month

    public Shipment(string recipient, string address, bool insurance, List<int> boxes, bool giftWrap = false)
    {
        Recipient = recipient; Address = address; Insurance = insurance; Boxes = boxes; GiftWrap = giftWrap;
    }

    public string Describe() =>
        $"{Recipient} at {Address}: {Boxes.Count} boxes, {Boxes.Sum()} lb" + (Insurance ? ", insurance" : "") + (GiftWrap ? ", gift wrap" : "");
}
```

```text
Last week: Sam at Oak Ave: 2 boxes, 7 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance
```

```java
class Shipment {
    final String recipient;
    String address;
    final boolean insurance;
    final List<Integer> boxes;
    final boolean giftWrap; // added last month

    Shipment(String recipient, String address, boolean insurance, List<Integer> boxes) {
        this(recipient, address, insurance, boxes, false);
    }

    Shipment(String recipient, String address, boolean insurance, List<Integer> boxes, boolean giftWrap) {
        this.recipient = recipient; this.address = address; this.insurance = insurance; this.boxes = boxes; this.giftWrap = giftWrap;
    }

    String describe() {
        int pounds = 0;
        for (int box : boxes) { pounds += box; }
        return recipient + " at " + address + ": " + boxes.size() + " boxes, " + pounds + " lb"
            + (insurance ? ", insurance" : "") + (giftWrap ? ", gift wrap" : "");
    }
}

void main() {
    Shipment lastWeek = new Shipment("Sam", "Oak Ave", true, new ArrayList<>(List.of(5, 2)), true);

    // The "same as last week" screen: copy each field by hand, then change what's new.
    Shipment thisWeek = new Shipment(lastWeek.recipient, "Cedar Ln", lastWeek.insurance, new ArrayList<>(lastWeek.boxes));
    thisWeek.boxes.add(8);

    IO.println("Last week: " + lastWeek.describe());
    IO.println("This week: " + thisWeek.describe());
}
```

```text
Last week: Sam at Oak Ave: 2 boxes, 7 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance
```

```python
class Shipment:
    def __init__(self, recipient, address, insurance, boxes, gift_wrap=False):  # gift_wrap added last month
        self.recipient = recipient
        self.address = address
        self.insurance = insurance
        self.boxes = boxes
        self.gift_wrap = gift_wrap

    def describe(self):
        text = f"{self.recipient} at {self.address}: {len(self.boxes)} boxes, {sum(self.boxes)} lb"
        if self.insurance:
            text += ", insurance"
        if self.gift_wrap:
            text += ", gift wrap"
        return text


last_week = Shipment("Sam", "Oak Ave", True, [5, 2], gift_wrap=True)

# The "same as last week" screen: copy each field by hand, then change what's new.
this_week = Shipment(last_week.recipient, "Cedar Ln", last_week.insurance, list(last_week.boxes))
this_week.boxes.append(8)

print("Last week: " + last_week.describe())
print("This week: " + this_week.describe())
```

```text
Last week: Sam at Oak Ave: 2 boxes, 7 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance
```

```javascript
class Shipment {
  constructor(recipient, address, insurance, boxes, giftWrap = false) { // giftWrap added last month
    this.recipient = recipient;
    this.address = address;
    this.insurance = insurance;
    this.boxes = boxes;
    this.giftWrap = giftWrap;
  }

  describe() {
    const pounds = this.boxes.reduce((sum, box) => sum + box, 0);
    return `${this.recipient} at ${this.address}: ${this.boxes.length} boxes, ${pounds} lb`
      + (this.insurance ? ", insurance" : "") + (this.giftWrap ? ", gift wrap" : "");
  }
}

const lastWeek = new Shipment("Sam", "Oak Ave", true, [5, 2], true);

// The "same as last week" screen: copy each field by hand, then change what's new.
const thisWeek = new Shipment(lastWeek.recipient, "Cedar Ln", lastWeek.insurance, [...lastWeek.boxes]);
thisWeek.boxes.push(8);

console.log("Last week: " + lastWeek.describe());
console.log("This week: " + thisWeek.describe());
```

```text
Last week: Sam at Oak Ave: 2 boxes, 7 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance
```

```typescript
class Shipment {
  recipient: string;
  address: string;
  insurance: boolean;
  boxes: number[];
  giftWrap: boolean; // added last month

  constructor(recipient: string, address: string, insurance: boolean, boxes: number[], giftWrap = false) {
    this.recipient = recipient;
    this.address = address;
    this.insurance = insurance;
    this.boxes = boxes;
    this.giftWrap = giftWrap;
  }

  describe(): string {
    const pounds = this.boxes.reduce((sum, box) => sum + box, 0);
    return `${this.recipient} at ${this.address}: ${this.boxes.length} boxes, ${pounds} lb`
      + (this.insurance ? ", insurance" : "") + (this.giftWrap ? ", gift wrap" : "");
  }
}

const lastWeek = new Shipment("Sam", "Oak Ave", true, [5, 2], true);

// The "same as last week" screen: copy each field by hand, then change what's new.
const thisWeek = new Shipment(lastWeek.recipient, "Cedar Ln", lastWeek.insurance, [...lastWeek.boxes]);
thisWeek.boxes.push(8);

console.log("Last week: " + lastWeek.describe());
console.log("This week: " + thisWeek.describe());
```

```text
Last week: Sam at Oak Ave: 2 boxes, 7 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance
```

This week's shipment has no gift wrap. The "same as last week" screen was written before gift wrap existed, and when gift wrap was added, it got a default of "no" so that old code would still compile. So the old copying code still compiled, and quietly dropped it. Every field added from now on is one more thing for that screen, and any other screen that copies shipments, to forget.

- **The symptom:** code outside an object rebuilds it field by field, to get one that's almost the same, and misses the newest field.
- **The cause:** only the shipment knows all of its fields, but the copying is done somewhere else.

## What would you try?

**Add the gift-wrap line to the copying code.** That fixes this month. Next month's "fragile" sticker needs the same fix, in every screen that copies.

**Look last week's order up and fill in this week's form by hand.** That's what the button was meant to save, and people forget fields too.

**Keep one shared shipment and change its address each week.** Then last week's record changes too, and the tracker can't say where last week's boxes went.

What we want is for the one thing that knows every field, the shipment itself, to do the copying.

## The fix: duplicate, then change

A presentation app's **Duplicate slide** works this way. You don't build the slide again from a blank page; you duplicate the one that's nearly right, then change the title. The copy has everything the original had, including the things you'd forget to redo.

![A presentation app's slide list on the left with a slide titled "Week 1 results" highlighted and a right-click menu open beside it, its option "Duplicate slide" selected; below it in the list, the new copy, the same slide with its title being edited to "Week 2 results"](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/630f2a2a25af49a593ed5521b166f9c4.webp)

In code, the shipment gets a `Copy` method. The screen asks last week's shipment to copy itself, then changes what's new. An object you copy to make new ones is a **prototype**. Here's a first try:

```csharp
Shipment lastWeek = new Shipment("Sam", "Oak Ave", true, new List<int> { 5, 2 }, giftWrap: true);

// Ask the shipment to copy itself, then change what's new.
Shipment thisWeek = lastWeek.Copy();
thisWeek.Address = "Cedar Ln";
thisWeek.Boxes.Add(8);

Console.WriteLine("Last week: " + lastWeek.Describe());
Console.WriteLine("This week: " + thisWeek.Describe());

class Shipment
{
    public string Recipient { get; }
    public string Address { get; set; }
    public bool Insurance { get; }
    public List<int> Boxes { get; }
    public bool GiftWrap { get; }

    public Shipment(string recipient, string address, bool insurance, List<int> boxes, bool giftWrap = false)
    {
        Recipient = recipient; Address = address; Insurance = insurance; Boxes = boxes; GiftWrap = giftWrap;
    }

    // A first try: every field copied, the list of boxes too... or is it?
    public Shipment Copy() => new Shipment(Recipient, Address, Insurance, Boxes, GiftWrap);

    public string Describe() =>
        $"{Recipient} at {Address}: {Boxes.Count} boxes, {Boxes.Sum()} lb" + (Insurance ? ", insurance" : "") + (GiftWrap ? ", gift wrap" : "");
}
```

```text
Last week: Sam at Oak Ave: 3 boxes, 15 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance, gift wrap
```

```java
class Shipment {
    final String recipient;
    String address;
    final boolean insurance;
    final List<Integer> boxes;
    final boolean giftWrap;

    Shipment(String recipient, String address, boolean insurance, List<Integer> boxes, boolean giftWrap) {
        this.recipient = recipient; this.address = address; this.insurance = insurance; this.boxes = boxes; this.giftWrap = giftWrap;
    }

    // A first try: every field copied, the list of boxes too... or is it?
    Shipment copy() { return new Shipment(recipient, address, insurance, boxes, giftWrap); }

    String describe() {
        int pounds = 0;
        for (int box : boxes) { pounds += box; }
        return recipient + " at " + address + ": " + boxes.size() + " boxes, " + pounds + " lb"
            + (insurance ? ", insurance" : "") + (giftWrap ? ", gift wrap" : "");
    }
}

void main() {
    Shipment lastWeek = new Shipment("Sam", "Oak Ave", true, new ArrayList<>(List.of(5, 2)), true);

    // Ask the shipment to copy itself, then change what's new.
    Shipment thisWeek = lastWeek.copy();
    thisWeek.address = "Cedar Ln";
    thisWeek.boxes.add(8);

    IO.println("Last week: " + lastWeek.describe());
    IO.println("This week: " + thisWeek.describe());
}
```

```text
Last week: Sam at Oak Ave: 3 boxes, 15 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance, gift wrap
```

```python
class Shipment:
    def __init__(self, recipient, address, insurance, boxes, gift_wrap=False):
        self.recipient = recipient
        self.address = address
        self.insurance = insurance
        self.boxes = boxes
        self.gift_wrap = gift_wrap

    # A first try: every field copied, the list of boxes too... or is it?
    def copy(self):
        return Shipment(self.recipient, self.address, self.insurance, self.boxes, self.gift_wrap)

    def describe(self):
        text = f"{self.recipient} at {self.address}: {len(self.boxes)} boxes, {sum(self.boxes)} lb"
        if self.insurance:
            text += ", insurance"
        if self.gift_wrap:
            text += ", gift wrap"
        return text


last_week = Shipment("Sam", "Oak Ave", True, [5, 2], gift_wrap=True)

# Ask the shipment to copy itself, then change what's new.
this_week = last_week.copy()
this_week.address = "Cedar Ln"
this_week.boxes.append(8)

print("Last week: " + last_week.describe())
print("This week: " + this_week.describe())
```

```text
Last week: Sam at Oak Ave: 3 boxes, 15 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance, gift wrap
```

```javascript
class Shipment {
  constructor(recipient, address, insurance, boxes, giftWrap = false) {
    this.recipient = recipient;
    this.address = address;
    this.insurance = insurance;
    this.boxes = boxes;
    this.giftWrap = giftWrap;
  }

  // A first try: every field copied, the list of boxes too... or is it?
  copy() { return new Shipment(this.recipient, this.address, this.insurance, this.boxes, this.giftWrap); }

  describe() {
    const pounds = this.boxes.reduce((sum, box) => sum + box, 0);
    return `${this.recipient} at ${this.address}: ${this.boxes.length} boxes, ${pounds} lb`
      + (this.insurance ? ", insurance" : "") + (this.giftWrap ? ", gift wrap" : "");
  }
}

const lastWeek = new Shipment("Sam", "Oak Ave", true, [5, 2], true);

// Ask the shipment to copy itself, then change what's new.
const thisWeek = lastWeek.copy();
thisWeek.address = "Cedar Ln";
thisWeek.boxes.push(8);

console.log("Last week: " + lastWeek.describe());
console.log("This week: " + thisWeek.describe());
```

```text
Last week: Sam at Oak Ave: 3 boxes, 15 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance, gift wrap
```

```typescript
class Shipment {
  recipient: string;
  address: string;
  insurance: boolean;
  boxes: number[];
  giftWrap: boolean;

  constructor(recipient: string, address: string, insurance: boolean, boxes: number[], giftWrap = false) {
    this.recipient = recipient;
    this.address = address;
    this.insurance = insurance;
    this.boxes = boxes;
    this.giftWrap = giftWrap;
  }

  // A first try: every field copied, the list of boxes too... or is it?
  copy(): Shipment { return new Shipment(this.recipient, this.address, this.insurance, this.boxes, this.giftWrap); }

  describe(): string {
    const pounds = this.boxes.reduce((sum, box) => sum + box, 0);
    return `${this.recipient} at ${this.address}: ${this.boxes.length} boxes, ${pounds} lb`
      + (this.insurance ? ", insurance" : "") + (this.giftWrap ? ", gift wrap" : "");
  }
}

const lastWeek = new Shipment("Sam", "Oak Ave", true, [5, 2], true);

// Ask the shipment to copy itself, then change what's new.
const thisWeek = lastWeek.copy();
thisWeek.address = "Cedar Ln";
thisWeek.boxes.push(8);

console.log("Last week: " + lastWeek.describe());
console.log("This week: " + thisWeek.describe());
```

```text
Last week: Sam at Oak Ave: 3 boxes, 15 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance, gift wrap
```

Gift wrap is back. But look at last week: **3 boxes, 15 lb.** Adding this week's box changed last week's shipment too.

## Shallow and deep copies

`Copy` copied each field, and for the list of boxes, it copied the *reference*: the note that says where the list is, not the list itself. So both shipments point at **one** list. Add a box through either one, and both see it. A copy that shares the things inside it with the original is a **shallow copy**. A copy that also copies what's inside, so it has its own list, is a **deep copy**.

![Shallow and deep copies as object diagrams. Shallow: last week's and this week's shipments both point to one list of boxes (5, 2, 8), so adding a box changed both. Deep: each shipment has its own list, last week 5 and 2, this week 5, 2 and 8](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/658c874a115644a78519ec9b42c6847b.webp)

The fix is one change inside `Copy`: give the copy a new list with the same boxes in it.

```csharp
Shipment lastWeek = new Shipment("Sam", "Oak Ave", true, new List<int> { 5, 2 }, giftWrap: true);

Shipment thisWeek = lastWeek.Copy();
thisWeek.Address = "Cedar Ln";
thisWeek.Boxes.Add(8);

Console.WriteLine("Last week: " + lastWeek.Describe());
Console.WriteLine("This week: " + thisWeek.Describe());

class Shipment
{
    public string Recipient { get; }
    public string Address { get; set; }
    public bool Insurance { get; }
    public List<int> Boxes { get; }
    public bool GiftWrap { get; }

    public Shipment(string recipient, string address, bool insurance, List<int> boxes, bool giftWrap = false)
    {
        Recipient = recipient; Address = address; Insurance = insurance; Boxes = boxes; GiftWrap = giftWrap;
    }

    // A deep copy: the copy gets its own list of boxes.
    public Shipment Copy() => new Shipment(Recipient, Address, Insurance, new List<int>(Boxes), GiftWrap);

    public string Describe() =>
        $"{Recipient} at {Address}: {Boxes.Count} boxes, {Boxes.Sum()} lb" + (Insurance ? ", insurance" : "") + (GiftWrap ? ", gift wrap" : "");
}
```

```text
Last week: Sam at Oak Ave: 2 boxes, 7 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance, gift wrap
```

```java
class Shipment {
    final String recipient;
    String address;
    final boolean insurance;
    final List<Integer> boxes;
    final boolean giftWrap;

    Shipment(String recipient, String address, boolean insurance, List<Integer> boxes, boolean giftWrap) {
        this.recipient = recipient; this.address = address; this.insurance = insurance; this.boxes = boxes; this.giftWrap = giftWrap;
    }

    // A deep copy: the copy gets its own list of boxes.
    Shipment copy() { return new Shipment(recipient, address, insurance, new ArrayList<>(boxes), giftWrap); }

    String describe() {
        int pounds = 0;
        for (int box : boxes) { pounds += box; }
        return recipient + " at " + address + ": " + boxes.size() + " boxes, " + pounds + " lb"
            + (insurance ? ", insurance" : "") + (giftWrap ? ", gift wrap" : "");
    }
}

void main() {
    Shipment lastWeek = new Shipment("Sam", "Oak Ave", true, new ArrayList<>(List.of(5, 2)), true);

    Shipment thisWeek = lastWeek.copy();
    thisWeek.address = "Cedar Ln";
    thisWeek.boxes.add(8);

    IO.println("Last week: " + lastWeek.describe());
    IO.println("This week: " + thisWeek.describe());
}
```

```text
Last week: Sam at Oak Ave: 2 boxes, 7 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance, gift wrap
```

```python
class Shipment:
    def __init__(self, recipient, address, insurance, boxes, gift_wrap=False):
        self.recipient = recipient
        self.address = address
        self.insurance = insurance
        self.boxes = boxes
        self.gift_wrap = gift_wrap

    # A deep copy: the copy gets its own list of boxes.
    def copy(self):
        return Shipment(self.recipient, self.address, self.insurance, list(self.boxes), self.gift_wrap)

    def describe(self):
        text = f"{self.recipient} at {self.address}: {len(self.boxes)} boxes, {sum(self.boxes)} lb"
        if self.insurance:
            text += ", insurance"
        if self.gift_wrap:
            text += ", gift wrap"
        return text


last_week = Shipment("Sam", "Oak Ave", True, [5, 2], gift_wrap=True)

this_week = last_week.copy()
this_week.address = "Cedar Ln"
this_week.boxes.append(8)

print("Last week: " + last_week.describe())
print("This week: " + this_week.describe())
```

```text
Last week: Sam at Oak Ave: 2 boxes, 7 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance, gift wrap
```

```javascript
class Shipment {
  constructor(recipient, address, insurance, boxes, giftWrap = false) {
    this.recipient = recipient;
    this.address = address;
    this.insurance = insurance;
    this.boxes = boxes;
    this.giftWrap = giftWrap;
  }

  // A deep copy: the copy gets its own list of boxes.
  copy() { return new Shipment(this.recipient, this.address, this.insurance, [...this.boxes], this.giftWrap); }

  describe() {
    const pounds = this.boxes.reduce((sum, box) => sum + box, 0);
    return `${this.recipient} at ${this.address}: ${this.boxes.length} boxes, ${pounds} lb`
      + (this.insurance ? ", insurance" : "") + (this.giftWrap ? ", gift wrap" : "");
  }
}

const lastWeek = new Shipment("Sam", "Oak Ave", true, [5, 2], true);

const thisWeek = lastWeek.copy();
thisWeek.address = "Cedar Ln";
thisWeek.boxes.push(8);

console.log("Last week: " + lastWeek.describe());
console.log("This week: " + thisWeek.describe());
```

```text
Last week: Sam at Oak Ave: 2 boxes, 7 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance, gift wrap
```

```typescript
class Shipment {
  recipient: string;
  address: string;
  insurance: boolean;
  boxes: number[];
  giftWrap: boolean;

  constructor(recipient: string, address: string, insurance: boolean, boxes: number[], giftWrap = false) {
    this.recipient = recipient;
    this.address = address;
    this.insurance = insurance;
    this.boxes = boxes;
    this.giftWrap = giftWrap;
  }

  // A deep copy: the copy gets its own list of boxes.
  copy(): Shipment { return new Shipment(this.recipient, this.address, this.insurance, [...this.boxes], this.giftWrap); }

  describe(): string {
    const pounds = this.boxes.reduce((sum, box) => sum + box, 0);
    return `${this.recipient} at ${this.address}: ${this.boxes.length} boxes, ${pounds} lb`
      + (this.insurance ? ", insurance" : "") + (this.giftWrap ? ", gift wrap" : "");
  }
}

const lastWeek = new Shipment("Sam", "Oak Ave", true, [5, 2], true);

const thisWeek = lastWeek.copy();
thisWeek.address = "Cedar Ln";
thisWeek.boxes.push(8);

console.log("Last week: " + lastWeek.describe());
console.log("This week: " + thisWeek.describe());
```

```text
Last week: Sam at Oak Ave: 2 boxes, 7 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance, gift wrap
```

Both lines are right now. The copying lives in the one class that knows every field, so when the "fragile" sticker arrives, it's added to `Shipment` and to `Copy` beside it, and every screen that duplicates shipments gets it.

![Prototype's roles: the same-as-last-week screen asks last week's shipment, the prototype, to copy itself; the shipment makes the copy, and the screen changes only what's new. The fields (recipient, address, insurance, boxes, gift wrap) are fenced: only the shipment knows them](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/9a56b6e1f5ad4de4a3a8e1e81bac889c.webp)

### The modern version: copies the language makes

Most languages can copy an object for you. The catch is that their quick copies are **shallow**, so the list still needs its own copy:

```csharp
Shipment lastWeek = new Shipment("Sam", "Oak Ave", true, new List<int> { 5, 2 }, GiftWrap: true);

// with copies the record; the list gets a new one with the extra box in it.
Shipment thisWeek = lastWeek with { Address = "Cedar Ln", Boxes = [.. lastWeek.Boxes, 8] };

Console.WriteLine("Last week: " + lastWeek.Describe());
Console.WriteLine("This week: " + thisWeek.Describe());

record Shipment(string Recipient, string Address, bool Insurance, List<int> Boxes, bool GiftWrap = false)
{
    public string Describe() =>
        $"{Recipient} at {Address}: {Boxes.Count} boxes, {Boxes.Sum()} lb" + (Insurance ? ", insurance" : "") + (GiftWrap ? ", gift wrap" : "");
}
```

```text
Last week: Sam at Oak Ave: 2 boxes, 7 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance, gift wrap
```

```java
// A record's list can be made unchangeable (List.copyOf), so sharing it is safe; each change makes a copy.
record Shipment(String recipient, String address, boolean insurance, List<Integer> boxes, boolean giftWrap) {
    Shipment {
        boxes = List.copyOf(boxes);
    }

    Shipment movedTo(String newAddress) { return new Shipment(recipient, newAddress, insurance, boxes, giftWrap); }

    Shipment withBox(int pounds) {
        List<Integer> more = new ArrayList<>(boxes);
        more.add(pounds);
        return new Shipment(recipient, address, insurance, more, giftWrap);
    }

    String describe() {
        int pounds = 0;
        for (int box : boxes) { pounds += box; }
        return recipient + " at " + address + ": " + boxes.size() + " boxes, " + pounds + " lb"
            + (insurance ? ", insurance" : "") + (giftWrap ? ", gift wrap" : "");
    }
}

void main() {
    Shipment lastWeek = new Shipment("Sam", "Oak Ave", true, List.of(5, 2), true);

    Shipment thisWeek = lastWeek.movedTo("Cedar Ln").withBox(8);

    IO.println("Last week: " + lastWeek.describe());
    IO.println("This week: " + thisWeek.describe());
}
```

```text
Last week: Sam at Oak Ave: 2 boxes, 7 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance, gift wrap
```

```python
import copy


class Shipment:
    def __init__(self, recipient, address, insurance, boxes, gift_wrap=False):
        self.recipient = recipient
        self.address = address
        self.insurance = insurance
        self.boxes = boxes
        self.gift_wrap = gift_wrap

    def describe(self):
        text = f"{self.recipient} at {self.address}: {len(self.boxes)} boxes, {sum(self.boxes)} lb"
        if self.insurance:
            text += ", insurance"
        if self.gift_wrap:
            text += ", gift wrap"
        return text


last_week = Shipment("Sam", "Oak Ave", True, [5, 2], gift_wrap=True)

# deepcopy copies the shipment and everything inside it.
this_week = copy.deepcopy(last_week)
this_week.address = "Cedar Ln"
this_week.boxes.append(8)

print("Last week: " + last_week.describe())
print("This week: " + this_week.describe())
```

```text
Last week: Sam at Oak Ave: 2 boxes, 7 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance, gift wrap
```

```javascript
// A plain object, and a function that describes one.
function describe(shipment) {
  const pounds = shipment.boxes.reduce((sum, box) => sum + box, 0);
  return `${shipment.recipient} at ${shipment.address}: ${shipment.boxes.length} boxes, ${pounds} lb`
    + (shipment.insurance ? ", insurance" : "") + (shipment.giftWrap ? ", gift wrap" : "");
}

const lastWeek = { recipient: "Sam", address: "Oak Ave", insurance: true, boxes: [5, 2], giftWrap: true };

// structuredClone copies the object and everything inside it.
const thisWeek = structuredClone(lastWeek);
thisWeek.address = "Cedar Ln";
thisWeek.boxes.push(8);

console.log("Last week: " + describe(lastWeek));
console.log("This week: " + describe(thisWeek));
```

```text
Last week: Sam at Oak Ave: 2 boxes, 7 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance, gift wrap
```

```typescript
type Shipment = { recipient: string; address: string; insurance: boolean; boxes: number[]; giftWrap: boolean };

// A plain object, and a function that describes one.
function describe(shipment: Shipment): string {
  const pounds = shipment.boxes.reduce((sum, box) => sum + box, 0);
  return `${shipment.recipient} at ${shipment.address}: ${shipment.boxes.length} boxes, ${pounds} lb`
    + (shipment.insurance ? ", insurance" : "") + (shipment.giftWrap ? ", gift wrap" : "");
}

const lastWeek: Shipment = { recipient: "Sam", address: "Oak Ave", insurance: true, boxes: [5, 2], giftWrap: true };

// structuredClone copies the object and everything inside it.
const thisWeek = structuredClone(lastWeek);
thisWeek.address = "Cedar Ln";
thisWeek.boxes.push(8);

console.log("Last week: " + describe(lastWeek));
console.log("This week: " + describe(thisWeek));
```

```text
Last week: Sam at Oak Ave: 2 boxes, 7 lb, insurance, gift wrap
This week: Sam at Cedar Ln: 3 boxes, 15 lb, insurance, gift wrap
```

**Where the languages differ.** C#'s `with`, Python's `copy.copy` and `dataclasses.replace`, and JavaScript's spread `{ ...lastWeek }` all make **shallow** copies: on their own, they'd share the list. Python's `copy.deepcopy` and JavaScript's `structuredClone` make **deep** ones; `structuredClone` copies plain data, not a class's methods, so it's used here on a plain object. Java's built-in `clone()` is hard to use safely, so Java code writes its own copy method, or does as the record above does: a list nobody can change can be shared without any risk.

## How it got its name

The shipment you copy from is the **prototype**, in the old sense of the word: the first one, that the others are made from. The **Prototype pattern** says: when an object is easier to copy than to build, let it copy itself. It's in the original 1994 book. (JavaScript's `prototype`, where objects borrow methods from another object, shares the name but is a different idea.)

## Where you've already used it

- "Duplicate" in a document, a spreadsheet tab or a slide; "Save As" on a file.
- C#'s `record` with `with`, Python's `copy` module, and JavaScript's `structuredClone`.
- A game that copies one enemy's settings to spawn twenty more.

## When not to use it

- **When the object is quick to make from scratch.** `new Box(5)` doesn't need a copy method.
- **When some fields must not be copied.** A copied package must get a new package number, and a copy must never share an open connection or a payment. Decide, field by field, what a copy gets.
- **When you can't tell how deep a copy should go.** If a shipment points at its customer, should a copy have a copy of the customer? (No: both shipments belong to the same Sam.) Say so in the copy method.

**How often you'll meet it:** now and then as a pattern, and every day as the shallow-copy bug (our estimate).

## Check yourself

2 questions to try on the lesson page.

## So what

When code keeps rebuilding an object to get one that's almost the same, let the object copy itself, and then change what's different. And when the object holds a list, decide whether the copy shares it, before a bug decides for you.

## Key terms

- [Prototype Pattern](https://www.ask-codey.com/glossary/prototype-pattern)
- [Shallow Copy](https://www.ask-codey.com/glossary/shallow-copy-software-development)
- [Deep Copy](https://www.ask-codey.com/glossary/deep-copy-software-development)

## Cheat sheets

- [Prototype: Duplicate, Then Change](https://www.ask-codey.com/cheat-sheets/dp-prototype-cheat-sheet)

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