Hint: Default == compares object identity, not data [OK]
Common Mistakes:
Assuming == compares data automatically
Expecting True because attributes match
Confusing syntax error with logic error
4. In a DDD model, a Value Object should be immutable. Which of the following code snippets violates this principle?
medium
A. class Money:
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency
B. class Money:
def __init__(self, amount, currency):
self._amount = amount
self._currency = currency
C. class Money:
def __init__(self, amount, currency):
self._amount = amount
self._currency = currency
@property
def amount(self):
return self._amount
D. class Money:
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency
def change_amount(self, new_amount):
self.amount = new_amount
Solution
Step 1: Recall immutability in Value Objects
Value Objects should not allow changes after creation to keep consistency.
Step 2: Identify mutable code
class Money:
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency
def change_amount(self, new_amount):
self.amount = new_amount has a method that changes the amount, violating immutability.
Final Answer:
Code with method changing amount violates immutability -> Option D
Quick Check:
Value Object must be immutable = no setters [OK]
Hint: Value Objects cannot change state after creation [OK]
Common Mistakes:
Allowing setters or methods that modify attributes
Confusing immutability with read-only properties only
Ignoring methods that change internal state
5. You are designing a DDD model for an online store. Which of the following best represents an Aggregate?
hard
A. An Order object that contains multiple OrderItems and enforces business rules
B. A single Product object with price and description
C. A database table storing customer addresses
D. A utility service that calculates discounts
Solution
Step 1: Understand Aggregate in DDD
An Aggregate is a cluster of related objects treated as a single unit with a root entity controlling consistency.
Step 2: Match options with Aggregate concept
An Order object that contains multiple OrderItems and enforces business rules describes an Order with multiple OrderItems and business rules, fitting Aggregate definition.
Final Answer:
An Order object containing multiple OrderItems and enforcing business rules -> Option A
Quick Check:
Aggregate = root entity + related objects [OK]
Hint: Aggregate = root entity plus related objects as one unit [OK]