Bird
Raised Fist0

In a DDD model, a Value Object should be immutable. Which of the following code snippets violates this principle?

medium๐Ÿ“ Analysis Q14 of Q15
LLD - Advanced LLD Concepts
In a DDD model, a Value Object should be immutable. Which of the following code snippets violates this principle?
Aclass Money: def __init__(self, amount, currency): self.amount = amount self.currency = currency
Bclass Money: def __init__(self, amount, currency): self._amount = amount self._currency = currency
Cclass Money: def __init__(self, amount, currency): self._amount = amount self._currency = currency @property def amount(self): return self._amount
Dclass Money: def __init__(self, amount, currency): self.amount = amount self.currency = currency def change_amount(self, new_amount): self.amount = new_amount
Step-by-Step Solution
Solution:
  1. Step 1: Recall immutability in Value Objects

    Value Objects should not allow changes after creation to keep consistency.
  2. 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.
  3. Final Answer:

    Code with method changing amount violates immutability -> Option D
  4. Quick Check:

    Value Object must be immutable = no setters [OK]
Quick Trick: Value Objects cannot change state after creation [OK]
Common Mistakes:
MISTAKES
  • Allowing setters or methods that modify attributes
  • Confusing immutability with read-only properties only
  • Ignoring methods that change internal state

Want More Practice?

15+ quiz questions ยท All difficulty levels ยท Free

Free Signup - Practice All Questions
More LLD Quizzes