Information Expert

Information Expert (GRASP)

"Assign a responsibility to the class that has the information needed to fulfill it." — Craig Larman, Applying UML and Patterns (2004)

"Tell, don't ask." — OOP folklore (often attributed to Alec Sharp, Smalltalk by Example, 1997; popularised by Hunt & Thomas, The Pragmatic Programmer, 1999). A related idea.


Core idea

A method (a function, a responsibility) should live in the class that already has the data to fulfil it. If something is computed "from the outside", that is a signal to move the computation to the data, not to pull the data to the computation.


Why it matters

Without Information Expert With Information Expert
Data leaks through getters Data stays encapsulated
Logic is scattered across "utilities" Logic lives where it naturally fits
A formula change means edits in N external places A formula change means one method in one class
Testing the formula requires mocking the data Tested through the object's method
"Anemic model": DTO classes plus services "Rich model": classes with behaviour
High coupling (everyone knows everything) Low coupling (behaviour is localised)

The most famous smell: Anemic Domain Model

Martin Fowler (2003): classes with only fields plus services with only functions.

❌ Anemic model

@dataclass
class Order:
    items: list[OrderItem]
    discount_rate: float

def calculate_total(order: Order) -> float:         # ← logic OUTSIDE
    subtotal = sum(item.price * item.qty for item in order.items)
    return subtotal * (1 - order.discount_rate)

def item_count(order: Order) -> int:                # ← also outside
    return sum(item.qty for item in order.items)

Here Order is a "struct with fields" and calculate_total is a "function over the struct". That is procedural code dressed in OOP clothing.

Symptoms of an anemic model

✅ Rich model (Information Expert)

@dataclass(frozen=True)
class OrderItem:
    name: str
    price: float
    qty: int

    def subtotal(self) -> float:                    # ← data here, method here
        return self.price * self.qty

@dataclass(frozen=True)
class Order:
    items: tuple[OrderItem, ...]
    discount_rate: float = 0.0

    def subtotal(self) -> float:
        return sum(item.subtotal() for item in self.items)   # ← delegates to OrderItem

    def total(self) -> float:
        return self.subtotal() * (1 - self.discount_rate)

    def item_count(self) -> int:
        return sum(item.qty for item in self.items)

    def has_item(self, name: str) -> bool:
        return any(item.name == name for item in self.items)

Now:

API user:

# Before:
total = calculate_total(order)
count = item_count(order)
has_milk = has_item(order, "Milk")

# Now:
total = order.total()
count = order.item_count()
has_milk = order.has_item("Milk")

Simple. Clear. Each method lives where you would look for it first.


"Tell, don't ask" — the older relative of Information Expert

A related idea from 1999: do not ask an object for data so you can do something with it. Tell the object to do it itself.

❌ Ask

if account.balance >= amount:           # ask for the data
    account.balance -= amount            # change it ourselves
    print(f"new balance: {account.balance}")
else:
    raise InsufficientFundsError(...)

✅ Tell

account.withdraw(amount)                 # ← command

withdraw now lives in Account, because Account has the data (balance) and knows the rule (>= amount). The caller does not know about balance, does not know the rule, does not touch the invariant.

"Tell, don't ask" is Information Expert phrased from the client's side.


Delegation through a chain of experts

A classic pattern: data lives at several levels, and each level is the expert at its level, delegating downward:

Order
  ├─ subtotal()
  │    └─ sum(item.subtotal() for item in self.items)
  │             ↓
  │       OrderItem.subtotal()
  │             └─ self.price * self.qty
  │
  └─ total()
        └─ self.subtotal() * (1 - self.discount_rate)

Order does not reach into item.price * item.qty. It asks for item.subtotal() and trusts the expert who knows how to compute it.

If OrderItem later gets a "buy 2, get 1 free" discount:

class OrderItem:
    def subtotal(self):
        free = self.qty // 3
        paid = self.qty - free
        return self.price * paid       # 3 at the price of 2

Order.subtotal() is not touched. It still calls item.subtotal(). The information expert encapsulated the change.


When Information Expert does not apply (caveats)

It is not a dogma. There are limits.

1. The expert would become a god class

If Order gets:

Then Order becomes a god class. GRASP Low Coupling & High Cohesion says: responsibilities that are not related to the class's main theme should live outside. Service classes (EmailService, PaymentGateway, InventoryService) are justified because they own their own information.

2. The information is spread across classes

What if a computation needs data from three classes?

def calculate_overdue_fine(book, member, current_date):
    days_late = (current_date - book.due_date).days
    return member.fine_per_day * max(days_late, 0)

Information is in three places:

No single full expert. So:

3. The data is not yet brought together

# Business operation: "subscribe"
def subscribe(user, plan, payment_method, today):
    ...

There is no natural aggregate here. User does not "know" about plan, Plan does not "know" about User. This is a use-case level operation that coordinates these objects. It naturally lives in a controller or service.


How to spot a violation

1. Getters are read more often than methods are called

Classes where 90% of accesses are obj.field and there are almost no methods — that is an anemia signal.

if order.items and order.discount_rate > 0 and order.items[0].price > 0:
    # ← deep accesses instead of order.has_active_discount()

2. The same computation in different places

If calculate_total(order) happens in view.py, email_sender.py, and report.py, sooner or later the formulas drift apart. The expert = one place.

3. Services with two or three "model" parameters

class OrderService:
    def calculate_total(self, order, customer, discount): ...
    def apply_promo(self, order, promo): ...
    def get_summary(self, order): ...

Every method takes order and does something with it. These are methods of Order, not of a service.

4. Test setup builds deep object trees via getter access

Tests that dig into internal representation instead of calling methods are another signal.


Information Expert and Python

Python is especially friendly to Information Expert.

@dataclass with methods is the norm

@dataclass(frozen=True)
class Money:
    amount: float
    currency: str

    def __add__(self, other):                    # ← this is Information Expert!
        if self.currency != other.currency: raise ...
        return Money(self.amount + other.amount, self.currency)

    def with_vat(self, rate: float) -> "Money":
        return Money(self.amount * (1 + rate), self.currency)

Information Expert in action: the methods are where the data is.

Dunder methods are Information Expert in Pythonic form

__len__, __eq__, __add__ — always Information Expert. The object that has the data itself implements the operation. Python is built on this principle.


Anti-patterns

1. A static utility class with everything

class OrderUtils:
    @staticmethod
    def total(order): ...
    @staticmethod
    def count(order): ...
    @staticmethod
    def has_item(order, name): ...

This is a procedure with a namespace wrapper. Move it into Order.

2. "Manager" / "Helper" / "Calculator" holding the object's state

class OrderCalculator:
    def __init__(self, order):
        self.order = order

    def total(self):
        return sum(i.price * i.qty for i in self.order.items)

A "calculator with a reference to Order" = Order's methods in disguise. This is not "split responsibility", it is "a separate class for the same responsibility". Move it.

3. Deep accesses obj.field1.field2.field3.method()

This is a Law of Demeter violation ("train wreck"). Instead of dragging through three levels:

total = order.customer.address.country.tax_rate * order.subtotal

Each level should give you what you need:

total = order.calculate_total_with_tax()         # Order knows how to ask down the chain

4. Logic inside setters

order.discount = 0.10                            # ← actually triggers a total recompute!

This is a hidden surprise. A setter should set, not compute. Use order.apply_discount(0.10) instead — explicit and honest.


Relationship to other principles

Principle How it relates
SRP Information Expert keeps cohesion high, so SRP is not violated
Encapsulation Behaviour next to data lets the data stay hidden
Tell, don't ask The behavioural form of the same principle
Law of Demeter "Do not poke into other people's internals" follows from Information Expert
High Cohesion (GRASP) A direct link: methods around one theme

Rules of thumb

  1. If a method takes object X and does something with it, that is almost always a method of X.
  2. Deep chains a.b.c.d are a signal. Encapsulate at a higher level.
  3. A stateless service with one or two model parameters is a method of one of those models.
  4. "Calculator" / "Helper" / "Utils" with one argument type is a method of that type.
  5. If a class is just a @dataclass with no methods, suspect anemia.
  6. Do not pull everything into one class. Balance against High Cohesion (god class is also an anti-pattern).
  7. Use-case operations (subscribe, checkout, register) are services, not methods of models. Different nature.

One-line summary

Behaviour follows the data. Whoever has the data to do the job, does the job. "Tell, don't ask."