Programming Search⌘K

Patternadvanced

Private class data

Also called private class data pattern, data object, private data class.

Private class data moves the fields of a class into a separate data object that only lets them be read. Even the methods of the class cannot then change a field that was meant to be set once.

Family
structural-design
Intent
Control write access to the attributes of a class by moving them into a separate data object, which the class creates in its constructor and which exposes the attributes only for reading.
Also called
Data object

Intent

Control write access to the attributes of a class, and separate the data from the methods that use it.1 The class moves its fields into a separate data object. The class creates the data object in its constructor, and the data object lets the fields be read but not written.

Problem

An Order has an id and a customer, which must not change after the order is created, and a list of items, which changes. All three are fields of the class, so every method of the class can write all three. A method that merges two orders copies the items, and, by mistake, also the id:

This code runs but gives a wrong answer on purpose.

class Order:
    def __init__(self, order_id, customer):
        self.order_id = order_id
        self.customer = customer
        self.items = []

    def merge(self, other):
        self.items += other.items
        self.order_id = other.order_id  # bug: the id must not change


a = Order(42, "ann")
b = Order(43, "bob")
b.items.append("pen")
a.merge(b)
print("order", a.order_id, "for", a.customer)
Output
order 43 for ann

SourceMaking gives the general case: a class may expose its attributes to manipulation when manipulation is no longer desirable, for example after construction.1 Some fields are set once but cannot be declared final, because the language has no such modifier, or because the value is computed in the constructor.

The forces are these:

  • Some fields must not change after construction, and some must.
  • The language cannot mark a field as final, or its final applies only to the reference and not to the object.
  • The protection must also hold against the methods of the class itself.

Solution

Create a data class and move into it every attribute that needs protection. The main class creates an instance of the data class through its constructor. The data class exposes each attribute through a getter, and through a setter only if the attribute must change later.1

 Order                                 OrderData (read-only)
 -----                                 ---------------------
 - data: OrderData  ----------------->  order_id   (getter only)
 - items: list      (still mutable)     customer   (getter only)
 + add(item)
 + describe()  -- reads data.order_id, data.customer

The pattern lets the designer remove the write privilege of attributes that are meant to be set only during construction, even from methods of the target class.1 It also reduces the number of fields of the class, because the protected fields become one object.1

Here the same bug fails at once, because the data object is frozen:2

from dataclasses import dataclass, FrozenInstanceError


@dataclass(frozen=True)
class OrderData:
    order_id: int
    customer: str


class Order:
    def __init__(self, order_id, customer):
        self._data = OrderData(order_id, customer)
        self.items = []

    def merge(self, other):
        self.items += other.items
        self._data.order_id = other._data.order_id  # the same bug


a = Order(42, "ann")
b = Order(43, "bob")
try:
    a.merge(b)
except FrozenInstanceError as e:
    print("merge failed:", e)
print("order", a._data.order_id, "for", a._data.customer)
Output
merge failed: cannot assign to field 'order_id'
order 42 for ann

Example

The example files show one Order in each language. Its id and customer are in a read-only data object, and its list of items stays in the class. The program adds one item to an order with two items, and prints:

order 42 for ann: 2 items
order 42 for ann: 3 items
Language Data object Read-only by
Python a frozen dataclass an exception on assignment2
JavaScript a frozen object in a private #data field Object.freeze and the private field
TypeScript a class with readonly properties the compiler
Java a record component fields that are private and final3
C# a positional record init accessors, which assign only during object construction4
C++ a struct held as a const member the compiler
Go a struct with unexported fields package privacy
Rust a struct with private fields in a module privacy: fields of a public struct stay private5
PythonGitHub
from dataclasses import dataclass


@dataclass(frozen=True)
class OrderData:
    order_id: int
    customer: str


class Order:
    def __init__(self, order_id: int, customer: str, items: list[str]) -> None:
        self._data = OrderData(order_id, customer)  # fixed after construction
        self.items = list(items)  # changes

    @property
    def order_id(self) -> int:
        return self._data.order_id

    @property
    def customer(self) -> str:
        return self._data.customer

    def add(self, item: str) -> None:
        self.items.append(item)

    def describe(self) -> str:
        return f"order {self.order_id} for {self.customer}: {len(self.items)} items"


order = Order(42, "ann", ["pen", "ink"])
print(order.describe())
order.add("paper")
print(order.describe())
Output
order 42 for ann: 2 items
order 42 for ann: 3 items
  • Verdict: idiom. A frozen dataclass raises FrozenInstanceError on assignment, and the properties show the fields for reading only.
  • object.__setattr__ can still write a frozen field, so the protection stops mistakes, not a determined caller.
#include <iostream>
#include <string>
#include <utility>
#include <vector>

struct OrderData {
    int order_id;
    std::string customer;
};

class Order {
public:
    Order(int order_id, std::string customer, std::vector<std::string> items)
        : data_{order_id, std::move(customer)}, items_(std::move(items)) {}

    int order_id() const { return data_.order_id; }
    const std::string& customer() const { return data_.customer; }
    void add(std::string item) { items_.push_back(std::move(item)); }

    std::string describe() const {
        return "order " + std::to_string(order_id()) + " for " + customer() + ": " +
               std::to_string(items_.size()) + " items";
    }

private:
    const OrderData data_;  // fixed after construction, also for the methods of Order
    std::vector<std::string> items_;  // changes
};

int main() {
    Order order(42, "ann", {"pen", "ink"});
    std::cout << order.describe() << "\n";
    order.add("paper");
    std::cout << order.describe() << "\n";
}
Output
order 42 for ann: 2 items
order 42 for ann: 3 items
  • Verdict: idiom. A const member can be set only in the constructor's initializer list, so an assignment in any method does not compile.
JavaGitHub
import java.util.ArrayList;
import java.util.List;

record OrderData(int orderId, String customer) {}

class Order {
    private final OrderData data; // fixed after construction
    private final List<String> items; // changes

    Order(int orderId, String customer, List<String> items) {
        this.data = new OrderData(orderId, customer);
        this.items = new ArrayList<>(items);
    }

    int orderId() { return data.orderId(); }
    String customer() { return data.customer(); }
    void add(String item) { items.add(item); }

    String describe() {
        return "order " + orderId() + " for " + customer() + ": " + items.size() + " items";
    }
}

public class Main {
    public static void main(String[] args) {
        Order order = new Order(42, "ann", List.of("pen", "ink"));
        System.out.println(order.describe());
        order.add("paper");
        System.out.println(order.describe());
    }
}
Output
order 42 for ann: 2 items
order 42 for ann: 3 items
  • Verdict: idiom. A record is the data class: its component fields are private and final, and it has accessors but no setters. For one or two fields, private final fields in Order give the same protection.
using System;
using System.Collections.Generic;

record OrderData(int OrderId, string Customer); // init-only properties

class Order
{
    private readonly OrderData data; // fixed after construction
    private readonly List<string> items; // changes

    public Order(int orderId, string customer, IEnumerable<string> items)
    {
        data = new OrderData(orderId, customer);
        this.items = new List<string>(items);
    }

    public int OrderId => data.OrderId;
    public string Customer => data.Customer;
    public void Add(string item) => items.Add(item);
    public string Describe() => $"order {OrderId} for {Customer}: {items.Count} items";
}

class Program
{
    static void Main()
    {
        var order = new Order(42, "ann", new[] { "pen", "ink" });
        Console.WriteLine(order.Describe());
        order.Add("paper");
        Console.WriteLine(order.Describe());
    }
}
Output
order 42 for ann: 2 items
order 42 for ann: 3 items
  • Verdict: idiom. The properties of a positional record have init accessors, so they can be set only during construction. A with expression makes a changed copy and leaves the original as it was.
JavaScriptGitHub
class Order {
  #data; // private field: code outside the class cannot reach it
  constructor(orderId, customer, items) {
    this.#data = Object.freeze({ orderId, customer }); // fixed after construction
    this.items = [...items]; // changes
  }
  get orderId() {
    return this.#data.orderId;
  }
  get customer() {
    return this.#data.customer;
  }
  add(item) {
    this.items.push(item);
  }
  describe() {
    return `order ${this.orderId} for ${this.customer}: ${this.items.length} items`;
  }
}

const order = new Order(42, "ann", ["pen", "ink"]);
console.log(order.describe());
order.add("paper");
console.log(order.describe());
Output
order 42 for ann: 2 items
order 42 for ann: 3 items
  • Verdict: idiom. Object.freeze makes the data object read-only, and the #data field keeps it away from callers.
TypeScriptGitHub
class OrderData {
  readonly orderId: number;
  readonly customer: string;
  constructor(orderId: number, customer: string) {
    this.orderId = orderId;
    this.customer = customer;
  }
}

class Order {
  readonly #data: OrderData; // fixed after construction
  items: string[]; // changes
  constructor(orderId: number, customer: string, items: string[]) {
    this.#data = new OrderData(orderId, customer);
    this.items = [...items];
  }
  get orderId(): number {
    return this.#data.orderId;
  }
  get customer(): string {
    return this.#data.customer;
  }
  add(item: string): void {
    this.items.push(item);
  }
  describe(): string {
    return `order ${this.orderId} for ${this.customer}: ${this.items.length} items`;
  }
}

const order = new Order(42, "ann", ["pen", "ink"]);
console.log(order.describe());
order.add("paper");
console.log(order.describe());
Output
order 42 for ann: 2 items
order 42 for ann: 3 items
  • Verdict: idiom. readonly makes the compiler reject an assignment after the constructor, also inside the methods of Order.
package main

import "fmt"

// orderData holds the fields that are fixed after construction. In a real
// program, Order and orderData live in their own package, so that code in
// other packages can read the fields only through the methods.
type orderData struct {
	orderID  int
	customer string
}

type Order struct {
	data  *orderData // fixed after construction
	items []string   // changes
}

func NewOrder(orderID int, customer string, items []string) *Order {
	return &Order{data: &orderData{orderID, customer}, items: append([]string(nil), items...)}
}

func (o *Order) OrderID() int       { return o.data.orderID }
func (o *Order) Customer() string   { return o.data.customer }
func (o *Order) Add(item string)    { o.items = append(o.items, item) }
func (o *Order) Describe() string {
	return fmt.Sprintf("order %d for %s: %d items", o.OrderID(), o.Customer(), len(o.items))
}

func main() {
	order := NewOrder(42, "ann", []string{"pen", "ink"})
	fmt.Println(order.Describe())
	order.Add("paper")
	fmt.Println(order.Describe())
}
Output
order 42 for ann: 2 items
order 42 for ann: 3 items
  • Verdict: idiom. Go has no final fields, so privacy comes from the package: unexported fields cannot be written from another package. The os package uses this form for File.
  • Inside the package, every method can still write the fields; the protection is only against other packages.
RustGitHub
mod order {
    pub struct OrderData {
        order_id: u32, // private: no code outside this module can write it
        customer: String,
    }

    impl OrderData {
        pub fn order_id(&self) -> u32 {
            self.order_id
        }
        pub fn customer(&self) -> &str {
            &self.customer
        }
    }

    pub struct Order {
        data: OrderData,    // fixed after construction
        items: Vec<String>, // changes
    }

    impl Order {
        pub fn new(order_id: u32, customer: &str, items: &[&str]) -> Order {
            Order {
                data: OrderData { order_id, customer: customer.to_string() },
                items: items.iter().map(|s| s.to_string()).collect(),
            }
        }
        pub fn add(&mut self, item: &str) {
            self.items.push(item.to_string());
        }
        pub fn describe(&self) -> String {
            format!("order {} for {}: {} items", self.data.order_id(), self.data.customer(), self.items.len())
        }
    }
}

fn main() {
    let mut order = order::Order::new(42, "ann", &["pen", "ink"]);
    println!("{}", order.describe());
    order.add("paper");
    println!("{}", order.describe());
}
Output
order 42 for ann: 2 items
order 42 for ann: 3 items
  • Verdict: idiom. The fields of a struct are private even when the struct is public, so the module boundary gives read-only access through methods. A shared reference &OrderData also cannot change the data.

Consequences

The benefits:

  • Fields that must not change cannot change, even through a bug in the class itself.
  • The class shows in one place which state is fixed and which state changes.
  • The data object can be passed, compared and copied as a value.

The costs:

  • One more class. Each protected class gets a data class, and each access goes through it.
  • Shallow protection. A read-only reference to a mutable object does not protect the object. A frozen data object that holds a list still lets callers change the list.
  • Little gain with modern types. Where the language has final fields, records or read-only properties, the language already gives the protection, and the extra object adds only indirection.

When not to use it

Do not use the pattern when the language can mark the field itself as final or read-only. A Java final field, a C# readonly field or a property with an init accessor gives the same protection with no extra class.4

Do not use the pattern for a class whose fields all change. There is nothing to protect, and the data object only adds a level of access.

Immutable value objects. A data object with no setters is an immutable value. Java records, C# records and Python frozen dataclasses make such an object in one declaration.342 See Immutability.

Indirection for safety. The Go os package stores the data of a File in a separate, unexported struct, so that clients cannot overwrite it.67

Known uses

  • Go: os/types.go at go1.25.0 defines File as a struct that only embeds a pointer to the unexported type file. os/file_unix.go says that the extra level of indirection ensures that no clients of os can overwrite this data, which could cause the finalizer to close the wrong file descriptor.67

References

  1. Private Class Data Design Pattern, SourceMaking, Intent; Problem; Discussion; Structure; Check list
  2. The Python Standard Library, dataclasses, Python 3.14, frozen; FrozenInstanceError; Frozen instances
  3. The Java Language Specification, Java SE 25 Edition, 8.10.3 Record Members (component fields)
  4. The init keyword, C# language reference, introduction
  5. The Rust Programming Language, Paths for Referring to an Item in the Module Tree, Making Structs and Enums Public
  6. Go go1.25.0 source, src/os/types.go, type File, lines 14 to 20
  7. Go go1.25.0 source, src/os/file_unix.go, type file, lines 55 to 66

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source