/protean:refactor-extract-value-objectfrom protean
Extracts value objects from primitive fields in Protean aggregates, entities, and commands. Detects primitive obsession patterns like raw strings/floats/integers representing domain concepts and refactors them into proper value objects with validation and behavior.
Ships in protean. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
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
extract_vo_*_before.pyassets are the intentional starting point (primitive obsession); the*_after.pyassets show the target.
Identify primitive field groups or single fields representing domain concepts, extract them into value objects, and update all references.
| Output | Purpose |
|---|---|
| New value object class | @domain.value_object with fields and optional behavior |
| Updated aggregate/entity | ValueObject(NewVO) replacing primitive fields |
| Updated commands/events | Fields aligned with new VO structure |
| Updated tests | Tests for the new VO and updated aggregate tests |
Fields that always travel together are a VO waiting to be extracted:
| Field pattern | Extract to |
|---|---|
amount + currency | Money |
street + city + state + zip_code + country | Address |
latitude + longitude | Coordinates |
first_name + last_name | PersonName |
start_date + end_date | DateRange |
quantity + unit | Measurement |
width + height + depth | Dimensions |
area_code + number + extension | PhoneNumber |
A single field that carries domain meaning beyond its raw type:
| Field pattern | Extract to |
|---|---|
email = String(...) | Email (with format validation) |
phone = String(...) | PhoneNumber (with format validation) |
price = Decimal(...) | Money (with currency) |
url = String(...) | Url (with format validation) |
sku = String(...) | SKU (with format rules) |
percentage = Float(...) | Percentage (with 0-100 constraint) |
The same field group appearing in 2+ aggregates is the strongest signal: extract once, use everywhere.
Scan aggregate and entity definitions for the patterns above. For each candidate, note:
Follow value-object patterns:
from decimal import Decimal as D
@domain.value_object
class Money:
amount = Decimal(precision=19, scale=4, required=True)
currency = String(max_length=3, default="USD")
def add(self, other: "Money") -> "Money":
if self.currency != other.currency:
raise ValueError(f"Cannot add {self.currency} and {other.currency}")
return Money(amount=self.amount + other.amount, currency=self.currency)
def multiply(self, factor: int | D) -> "Money":
return Money(
amount=(self.amount * factor).quantize(D("0.0001")),
currency=self.currency,
)
Key decisions:
Float becomes Decimal(precision=19, scale=4), because a float cannot hold most cents exactly@invariant.post for concept-level validationIn each aggregate/entity, replace the field group with a ValueObject field:
# Before
@domain.aggregate
class Order:
total_amount = Decimal(precision=19, scale=4, default=D(0))
total_currency = String(default="USD")
# After
@domain.aggregate
class Order:
total = ValueObject(Money)
Replace inline calculations with VO methods:
# Before
def apply_discount(self, percentage):
self.total_amount = self.total_amount * (1 - D(percentage) / 100)
# After
def apply_discount(self, percentage):
self.total = self.total.multiply(1 - D(percentage) / 100)
Decide: flatten or nest?
# Option A: Flatten (simpler for API consumers)
@domain.command(part_of="Order")
class PlaceOrder:
amount = Decimal(precision=19, scale=4, required=True)
currency = String(default="USD")
# Option B: Nest (preserves VO semantics)
@domain.command(part_of="Order")
class PlaceOrder:
total = ValueObject(Money, required=True)
For events, flattening is often preferred since events are read by many consumers.
# fragment
# Before
assert order.total_amount == D("59.98")
assert order.total_currency == "USD"
# After
assert order.total.amount == D("59.98")
assert order.total.currency == "USD"
Extracting without behavior: A VO with only fields and no methods is often premature. Ask: does this concept have operations (add, compare, format)?
Over-extracting: Not every pair of fields is a VO. created_at + updated_at are
independent timestamps, not a "TimeRange".
Breaking event schemas: If events are persisted (event store), changing field structure
is a schema change. Add __version__ bump and an upcaster.
Forgetting HasMany entities: If the primitive fields are on entities inside a HasMany,
update those too.
Losing default values: When moving default=D(0) from the aggregate to the VO,
make sure the VO field or the aggregate ValueObject() field carries the default.
Putting a mutable collection on the VO: a value object is compared by value and must
stay immutable. A List or Dict field gives it mutable internal state, so two instances
that should be equal can drift apart and value equality breaks. check reports this as
VALUE_OBJECT_MUTABLE_FIELD. Move the collection onto the containing entity or aggregate,
or, if the items form a concept with its own identity, model them as an entity the aggregate
references.
check and resolve what it reportsassets/extract_vo_address_after.py (opens in a new tab)assets/extract_vo_address_before.py (opens in a new tab)assets/extract_vo_money_after.py (opens in a new tab)assets/extract_vo_money_before.py (opens in a new tab)references/anti-patterns.md (opens in a new tab)references/common-value-objects.md (opens in a new tab)references/migration-guide.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub proteanhq/protean --plugin protean39 skills in this plugin
/add-commandAdd a complete command flow to an existing aggregate. It creates a command class, a FastAPI API endpoint, and a command handler with repository logic. This is the primary workflow for adding write operations to a Protean domain. Use when the user wants to "add a command", "add an action", "add an operation", "expose a write endpoint", "create a command flow", "wire up a POST endpoint", "add a new operation to an aggregate", or describes an action like "I want users to be able to [verb] a [thing]" (e.g., "place an order", "register a user", "cancel a reservation"). This workflow composes the command, command-handler, and api-endpoint element skills./add-domain-service-flowBuild a domain service flow in Protean for business logic that spans two or more aggregates. Domain services are stateless, encapsulate cross-aggregate business rules, and run pre/post invariants for validation. They are used when business logic doesn't naturally belong to a single aggregate. Wire them into command handlers or application services for persistence. Use when the user asks to "add a domain service", "implement cross-aggregate logic", "coordinate multiple aggregates", "add a business operation spanning aggregates", "validate across aggregates", or when they describe scenarios like "placing an order checks inventory and reserves stock", "transferring funds between accounts", "scheduling involves both resource and calendar".Other plugins' skills for the same job