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
- Classes are
@dataclasswith no methods. - Services are functions with no state.
- Every service takes 3-5 "model" parameters.
- A lot of
order.discount_rate,order.items[0].price— deep accesses. - Tests need fake orders with full data trees.
✅ 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:
OrderItem.subtotal()becauseOrderItemhaspriceandqty. It is the expert.Order.subtotal()becauseOrderhasitems. It is the expert over the collection.Order.total()becauseOrderknows bothsubtotalanddiscount_rate.
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:
total()(fine)validate()(fine)send_confirmation_email()(❌ that is email logic, not Order)charge_card()(❌ that is payment, not Order)generate_invoice_pdf()(❌ that is rendering)update_inventory()(❌ that is the warehouse)
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:
book.due_date— inBookmember.fine_per_day— inMembercurrent_date— a parameter
No single full expert. So:
- If the logic is more about the member → put
Member.calculate_fine(book, current_date). - If it is domain-specific, not class-specific → move it to a service (
OverdueFineCalculator). That is Pure Fabrication.
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
- If a method takes object X and does something with it, that is almost always a method of X.
- Deep chains
a.b.c.dare a signal. Encapsulate at a higher level. - A stateless service with one or two model parameters is a method of one of those models.
- "Calculator" / "Helper" / "Utils" with one argument type is a method of that type.
- If a class is just a
@dataclasswith no methods, suspect anemia. - Do not pull everything into one class. Balance against High Cohesion (god class is also an anti-pattern).
- 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."