Value Objects and Mutability in OOP

ghulam_mujtaba_247

Ghulam Mujtaba

Posted on July 28, 2024

Value Objects and Mutability in OOP

Value objects are immutable objects that represent a set of values. They are used to encapsulate data and behavior, and are often used in domain-driven design.

Characteristics of Value Objects:

  • Immutable (cannot be changed once created)
  • Equal by value (not by reference)
  • No identity (no unique ID)
  • Can be used as array keys or hash map keys

Mutability:

Mutability refers to the ability of an object to change its state after creation.

Types of Mutability:

  • Mutable: Can change state after creation (e.g., arrays, objects with setters)
  • Immutable: Cannot change state after creation (e.g., value objects, strings)

Best Practices:

  • Use immutable objects when possible (e.g., value objects, data transfer objects)
  • Use mutable objects when necessary (e.g., entities, domain objects)
  • Avoid mixing mutable and immutable objects in the same class
<?php 

class Money {
  private $amount;
  private $currency;

  public function __construct($amount, $currency) {
    $this->amount = $amount;
    $this->currency = $currency;
  }

  public function getAmount() {
    return $this->amount;
  }

  public function getCurrency() {
    return $this->currency;
  }

  public function equals(Money $other) {
    return $this->amount === $other->amount && $this->currency === $other->currency;
  }
}
Enter fullscreen mode Exit fullscreen mode

Benefits of Immutable Objects:

  • Thread-safety
  • Easy to reason about and test
  • Can be used as cache keys or hash map keys
  • Reduces side effects and bugs

By using value objects and controlling mutability, we can write more predictable, maintainable, and scalable code in PHP OOP.

💖 💪 🙅 🚩
ghulam_mujtaba_247
Ghulam Mujtaba

Posted on July 28, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related