Refactor Move Logic To Aggregate
ASecurityMove business logic from handlers, services, or endpoints into aggregate methods where it belongs. Detects "logic leak" (validation, calculations, state transitions, and business rules scattered outside the domain model) and refactors them into rich aggregate methods with proper invariants. Use when the user says "move logic to aggregate", "handler is too fat", "fix logic leak", "enrich my aggregate", "make aggregate rich", "handler has too much logic", "anemic domain model", or when an audit...
- 46 stars
- 0 votes
- 0 copies
- 4 views
- Added September 20, 2026
Security analysis
100/100Pro scans all 5 files and shows the line behind each finding
npx -y skills add proteanhq/protean --skill refactor-move-logic-to-aggregate --agent claude-codeAre you the author of Refactor Move Logic To Aggregate?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/proteanhq-refactor-move-logic-to-aggregate)---
name: refactor-move-logic-to-aggregate
description: >
Move business logic from handlers, services, or endpoints into aggregate methods where it belongs.
Detects "logic leak" (validation, calculations, state transitions, and business rules scattered
outside the domain model) and refactors them into rich aggregate methods with proper invariants.
Use when the user says "move logic to aggregate", "handler is too fat", "fix logic leak",
"enrich my aggregate", "make aggregate rich", "handler has too much logic", "anemic domain model",
or when an audit identifies logic leaks or anemic aggregates.
license: Apache-2.0
compatibility: "Requires Python 3.11+, protean framework"
metadata:
author: proteanhq
version: "0.1"
category: workflow
composes: [aggregate, command-handler, event-handler]
diagnostic_codes: [AGGREGATE_NO_INVARIANTS]
---
# Refactor: Move Logic to Aggregate
> **Illustrative, guided refactoring.** This is a before→after walkthrough, not an
> automated transform: recognize the smell and apply the change yourself, adapting to the
> code at hand. The `move_logic_*_before.py` asset is the intentional starting point
> (anemic aggregate / fat handler); the `*_after.py` asset shows the rich-aggregate target.
Identify business logic that has leaked out of aggregates into handlers, services, or endpoints,
and move it back into rich aggregate methods with proper invariants and events.
## What this produces
| Output | Purpose |
|--------|---------|
| **Rich aggregate methods** | Business logic encapsulated in the aggregate |
| **Aggregate invariants** | Validation rules as `@invariant.post` decorators |
| **Thin handlers** | Handlers reduced to load → call → persist |
| **Updated tests** | Tests for aggregate behavior, not handler internals |
## Detection patterns
### The "controller handler"
Handler does validation, calculation, construction, and persistence:
```python
# fragment
# RED FLAG: handler has 10+ lines of logic
@handle(PlaceOrder)
def place_order(self, command):
if not command.items: # Validation
raise ValidationError(...)
total = sum(i.price * i.qty ...) # Calculation
if total > MAX: # Business rule
raise ValidationError(...)
order = Order(total=total, status="PLACED") # Construction
domain.repository_for(Order).add(order)
```
### The "anemic aggregate"
Aggregate is a data bag: no methods, no invariants:
```python
# fragment
# RED FLAG: only fields, no behavior
@domain.aggregate
class Order:
customer_id = String(required=True)
total = Decimal(precision=19, scale=4, default=0)
status = String(default="DRAFT")
# No methods!
```
### Specific signals
| Signal | Where found | What to move |
|--------|------------|-------------|
| `if` + `raise ValidationError` | Handler | `@invariant.post` on aggregate |
| Arithmetic / calculations | Handler | Aggregate method |
| `self.status = "..."` | Handler setting aggregate fields | Aggregate state-transition method |
| Multiple attribute assignments | Handler building aggregate state | Aggregate factory or method |
| `if status != "X": raise` | Handler guard clause | Aggregate method pre-condition |
## Process
### Step 1: Identify the logic to move
Read the handler and categorize each line:
| Line | Category | Destination |
|------|----------|-------------|
| `if not command.items: raise` | Validation | Aggregate invariant or method guard |
| `total = sum(...)` | Calculation | Aggregate method |
| `if total > MAX: raise` | Business rule | Aggregate invariant |
| `order.status = "PLACED"` | State transition | Aggregate method |
| `repo.add(order)` | Persistence | Stays in handler |
| `order = Order(...)` | Construction | Stays in handler (or factory) |
### Step 2: Create aggregate methods
The order's methods use a `Money` value object, a `LineItem` entity and an
`OrderPlaced` event. The handler in Step 4 takes a `PlaceOrder` command:
```python
@domain.value_object
class Money:
amount = Decimal(precision=19, scale=4, required=True)
currency = String(max_length=3, default="USD")
@domain.entity(part_of="Order")
class LineItem:
product_id = String(required=True)
quantity = Integer(required=True, min_value=1)
unit_price = ValueObject(Money, required=True)
@domain.event(part_of="Order")
class OrderPlaced:
order_id = Identifier(required=True)
total = Decimal(precision=19, scale=4, required=True)
@domain.command(part_of="Order")
class PlaceOrder:
customer_id = String(required=True)
items = List(content_type=Dict)
```
For each group of logic, create an aggregate method on `Order`: here `place()` and
`_calculate_total()`. Step 3 shows the whole class, with these methods and its
invariants.
### Step 3: Add invariants
Move validation from handlers into `@invariant.post`. With the methods from Step
2, the `Order` class reads:
```python
from decimal import Decimal as D
from protean.exceptions import ValidationError
@domain.aggregate
class Order:
customer_id = String(required=True)
items = HasMany(LineItem)
total = ValueObject(Money)
status = String(default="DRAFT")
def place(self, items: list[dict]) -> None:
"""Place the order with the given items."""
for item_data in items:
self.add_items(LineItem(**item_data))
self.total = self._calculate_total()
self.status = "PLACED"
self.raise_(OrderPlaced(order_id=self.id, total=self.total.amount))
def _calculate_total(self) -> Money:
"""Sum all line item totals."""
total = D(0)
for item in self.items:
total += item.unit_price.amount * item.quantity
return Money(amount=total)
@invariant.post
def must_have_items_when_placed(self):
"""A placed order must have at least one item."""
if self.status == "PLACED" and not self.items:
raise ValidationError({"items": ["Placed order must have items"]})
@invariant.post
def total_must_not_exceed_maximum(self):
"""Order total cannot exceed $50,000."""
if self.total and self.total.amount > 50000:
raise ValidationError({"total": ["Exceeds maximum order amount"]})
```
Placing an order with one line sets the total from that line:
```python
domain.init(traverse=False)
with domain.domain_context():
order = Order(customer_id="CUST-001")
order.place(
items=[
{"product_id": "P-1", "quantity": 2, "unit_price": Money(amount=D("10.00"))}
]
)
assert order.total.amount == D("20.00")
```
Do not skip this step. An aggregate that ends the refactor with rich methods but no
`@invariant.pre` or `@invariant.post` is still reported as `AGGREGATE_NO_INVARIANTS`: the
logic moved off the handler, but the consistency boundary enforces nothing. The rules you
deleted from the handler in Step 1 are the invariants to declare here.
### Step 4: Slim down the handler
The handler becomes load → call → persist:
```python
@domain.command_handler(part_of=Order)
class OrderCommandHandler:
@handle(PlaceOrder)
def place_order(self, command: PlaceOrder) -> None:
order = Order(customer_id=command.customer_id)
order.place(items=command.items)
domain.repository_for(Order).add(order)
```
**The ideal handler is 3-5 lines**: load/create aggregate, call one method, persist.
### Step 5: Move tests to aggregate level
A test that drives the handler checks the rule through its internals:
```python
# fragment
# Before: testing handler internals
def test_place_order_validates_items():
with pytest.raises(ValidationError):
handler.place_order(PlaceOrder(items=[]))
```
Test the aggregate's behavior directly instead:
```python
import pytest
from protean.exceptions import ValidationError
# After: testing aggregate behavior
def test_order_must_have_items_when_placed():
order = Order(customer_id="CUST-001")
with pytest.raises(ValidationError):
order.place(items=[]) # Invariant fires
```
## Common mistakes
1. **Moving persistence into the aggregate**: `repository.add()` stays in the handler.
Aggregates don't know about persistence.
2. **Creating a method per field**: If the handler sets 3 fields, create ONE method
that captures the business operation, not 3 setter methods.
3. **Leaving events in the handler**: `raise_()` belongs inside the aggregate method,
not in the handler after calling the method.
4. **Over-guarding**: Not every `if` is an invariant. Simple null checks in handlers
(`if not command.customer_id`) are often handled by field `required=True`.
## Examples
- Ticket: [before](assets/move_logic_ticket_before.py) and [after](assets/move_logic_ticket_after.py)
## Detailed references
- [Identifying logic leaks](references/identifying-logic-leaks.md): Heuristics and examples
- [Anti-patterns](references/anti-patterns.md): Common refactoring mistakes
## Related skills
- [aggregate](../aggregate/SKILL.md): Aggregate patterns
- [command-handler](../command-handler/SKILL.md): Handler patterns
- [audit-domain](../audit-domain/SKILL.md): Detects logic leaks
## Verify your work
- [Verify with check](../../references/verify-with-check.md): run `check` and resolve what it reports
Files in this skill
- SKILL.md
- assets/move_logic_ticket_after.py
- assets/move_logic_ticket_before.py
- references/anti-patterns.md
- references/identifying-logic-leaks.md
Attribution
Related skills
View all in testing →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.