Creator

Creator (GRASP)

"Assign class B the responsibility to create an instance of class A if one of these is true: B contains/aggregates A, B records A, B closely uses A, or B has the initializing data for A." — Craig Larman, Applying UML and Patterns


Core idea

Object A should be created by whoever is naturally connected to it: the container, the aggregator, the user, or the owner of the data needed to initialise it. This centralises the creation logic, hides the initialisation details, and gives you one place to change later.


Why it matters

Without Creator With Creator
Objects are created "wherever" Creation lives in one place
Every client remembers all the parameters The client calls one simple method
Initialisation details leak to the caller Details stay inside the Creator
Easy to forget created_at, likes=0, parent=... The method sets defaults itself
The object can be created in an inconsistent state The method guarantees consistency
Tests create objects in different ways One path for creation, one path for testing

Four indicators — who should be the Creator

Larman gives four signs (sometimes split into five by separating containment from aggregation). If at least one matches, class B is a natural Creator for A:

1. B is the container for A (composition)

class Order:
    def add_item(self, name, price, qty):
        item = OrderItem(name, price, qty)    # ← Order contains items
        self._items.append(item)

Order contains OrderItem. It is natural for Order to create them.

2. B aggregates A

class Library:
    def register_book(self, title, isbn):
        book = Book(title, isbn, available=True)    # ← Library aggregates books
        self._books[isbn] = book

Library is not strictly a "container" (books exist outside the library), but it aggregates the collection.

3. B records A

class AuditLog:
    def record(self, user_id, action):
        entry = AuditEntry(user_id, action, timestamp=datetime.now())
        self._entries.append(entry)

AuditLog records individual AuditEntry objects. Creating the entry is a natural part of recording.

4. B closely uses A

class HttpClient:
    def get(self, url):
        request = HttpRequest(method="GET", url=url, headers=self._default_headers)
        return self._send(request)

HttpClient closely uses HttpRequest: it creates it, processes it, returns the response.

5. B has the initialising data

class User:
    def create_session(self) -> Session:
        return Session(
            user_id=self.id,                 # ← from self
            ip_address=self.last_ip,         # ← from self
            created_at=datetime.now(),
        )

User has id and last_ip — exactly what Session needs. Other classes do not have this data, so User is the natural Creator.

Which one wins when several apply?

Larman does not give a strict ranking. The rule is "the more criteria match, the more reliable the choice". A useful heuristic: container / aggregator is usually the strongest signal, because it already owns the object structurally.


Before / after example: Comments on a Post

❌ Without Creator — scattered logic

@dataclass(frozen=True)
class Comment:
    author: str
    text: str
    created_at: datetime
    likes: int

@dataclass
class Post:
    title: str
    author: str
    comments: list[Comment]

# The comment is created OUTSIDE, with all the details:
post = Post(title="Hello", author="alice", comments=[])

new_comment = Comment(
    author="bob",
    text="Great post!",
    created_at=datetime.now(),    # ← remember this
    likes=0,                       # ← and this
)
post.comments.append(new_comment)

# Somewhere else, the same again:
spam = Comment(author="charlie", text="...", created_at=datetime.now(), likes=0)
post.comments.append(spam)

# A welcome comment:
def welcome(post, user):
    c = Comment(author="system", text=f"Welcome {user}", created_at=datetime.now(), likes=0)
    post.comments.append(c)

Problems:

✅ With Creator — the Post creates its Comments

@dataclass(frozen=True)
class Comment:
    author: str
    text: str
    created_at: datetime
    likes: int = 0

class Post:
    def __init__(self, title: str, author: str):
        self.title = title
        self.author = author
        self._comments: list[Comment] = []

    def add_comment(self, author: str, text: str) -> Comment:
        """Post is the Creator of its Comments."""
        comment = Comment(
            author=author,
            text=text,
            created_at=datetime.now(),
        )
        self._comments.append(comment)
        return comment

    @property
    def comments(self) -> tuple[Comment, ...]:
        return tuple(self._comments)

# Caller, simplified:
post = Post(title="Hello", author="alice")
post.add_comment(author="bob", text="Great post!")
post.add_comment(author="charlie", text="...")

# Welcome:
def welcome(post, user):
    post.add_comment(author="system", text=f"Welcome {user}")

What changed:


Creator and Information Expert are often the same idea

One of the five indicators is "has the initialising data". That is a direct case of Information Expert applied to creation:

Who has the data needed to build X? That one creates it.

If only User has id and last_ip to pass into Session(user_id, ip_address), then User.create_session() follows directly from Information Expert.


When the Creator is not obvious — use cases and workflows

Some objects do not belong to any existing class. They are transient working objects or workflow results:

# Order does not "contain" CheckoutResult.
# CheckoutResult is the RESULT of the checkout operation.

class CheckoutResult:
    transaction_id: str
    total: float
    success: bool

# Should Order create CheckoutResult? Probably not. It is a result, not a part of Order.

Here the Creator is the CheckoutService (use case):

class CheckoutService:
    def checkout(self, order: Order) -> CheckoutResult:
        tx_id = self._payment.charge(order.total(), order.card_token)
        return CheckoutResult(transaction_id=tx_id, total=order.total(), success=True)

A use-case service as Creator is fine for transient objects (results, events, snapshots).


Factory Method and Builder — extensions of Creator

Factory Method (GoF)

When the creation logic is more complex and has variants:

class User:
    def create_admin_session(self) -> Session:
        return Session(user_id=self.id, role="admin", ttl=3600)

    def create_readonly_session(self) -> Session:
        return Session(user_id=self.id, role="readonly", ttl=86400)

Each factory method is a separate variant. The caller does not know about Session or its fields.

Builder (GoF)

When the object has many parameters and their combinations are tricky:

class HttpRequestBuilder:
    def with_method(self, m): ...
    def with_url(self, u): ...
    def with_header(self, k, v): ...
    def with_body(self, b): ...
    def build(self) -> HttpRequest: ...

request = (HttpRequestBuilder()
    .with_method("POST")
    .with_url("/api/users")
    .with_header("Auth", "Bearer xxx")
    .with_body('{"name": "John"}')
    .build())

Builder is a fully fledged Creator with its own state. Worth it when:

YAGNI warning: Builder is often over-engineered for simple cases. @dataclass(kw_only=True) with defaults is rarely worse.


Anti-patterns

1. A "service" that only creates

class OrderItemFactory:
    def create(self, name, price, qty) -> OrderItem:
        return OrderItem(name, price, qty)

If there is no complex creation logic, this is an extra class. The constructor OrderItem(name, price, qty) is enough. YAGNI.

2. A creator without a link to the object

class OrderService:
    def add_item_to_order(self, order, name, price, qty):
        item = OrderItem(name, price, qty)
        order.items.append(item)             # ← OrderService reaches into Order's internals

This is anemic Order + service again. Move add_item into Order.

3. Creation by direct access to internal state

order = Order()
order.items.append(OrderItem(...))            # ← bypassing the API

This is a signal that add_item does not exist yet. The caller should go through a method. Once Order.add_item exists, access to order.items should be read-only (a property returning a tuple).

4. A Creator that knows too much about the created object

class Order:
    def add_item(self, name, price, qty, manufacturer, sku, category, stock_id, ...):
        item = OrderItem(name, price, qty)
        # 5 parameters ignored!

If add_item takes 10 parameters and only 3 are for the item, something is off with the split. Maybe Product should create its own ProductInfo, and Order should just do add_item(product, qty).

5. Direct constructors in tests that should go through the Creator

def test_order_total():
    order = Order(title="Test")
    order._items.append(OrderItem("A", 10, 2))    # ← bypassing the API!

If tests need a "convenient" way to construct, add a test factory (@classmethod from_items(cls, items): ...) instead of breaking encapsulation.


Creation through @classmethod — the Pythonic factory

class User:
    def __init__(self, name: str, email: str, created_at: datetime):
        self.name = name
        self.email = email
        self.created_at = created_at

    @classmethod
    def new(cls, name: str, email: str) -> "User":
        """Create a new user (Creator with defaults)."""
        return cls(name=name, email=email, created_at=datetime.now())

    @classmethod
    def from_db_row(cls, row: dict) -> "User":
        """Reconstruct from the database (a different form of creation)."""
        return cls(**row)

@classmethod is the standard Python pattern for named constructors (User.new(...), User.from_db_row(...)). Do not mix this with __init__, which has one canonical contract.


The number-one anti-pattern: "create, forget to link"

post = Post(...)
comment = Comment(...)           # ← created
# ... [somewhere we forget post.comments.append(comment)]
# Comment lives in memory but is registered nowhere

A classic mistake the Creator pattern removes entirely. If the only path is post.add_comment(...), which both creates and links, you cannot forget.


Relationship to other principles

Principle How it relates
Information Expert One of the indicators ("has initialising data") is direct Information Expert
High Cohesion (GRASP) Creator + container is a natural unit
Encapsulation The Creator hides construction details
DRY One path for creation, one place to change
Tell, don't ask post.add_comment(...) instead of post.comments.append(Comment(...))

Rules of thumb

  1. Whoever contains it, creates it. First instinct.
  2. The method name is a verb from context. add_comment, register_book, record_event. Not create_comment.
  3. The method takes the minimum parameters — only what the caller actually knows. Defaults, timestamps, ids are set by the Creator itself.
  4. Return the created object. The caller may want to use it. return comment.
  5. Avoid Builder / Factory classes for simple cases. @classmethod is usually enough.
  6. Tests create through the same API that production uses. Otherwise the test checks a path that does not exist in production.
  7. If the context is outside (Composition Root, use-case service), the service creates, not the container.

One-line summary

The object is created by whoever uses, stores, aggregates, or is closely tied to it. The caller gives the minimum of details; the Creator owns the rest.