DEV Community

Ghulam Mujtaba
Ghulam Mujtaba

Posted on

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.

Image of Bright Data

Maintain Seamless Data Collection – No more rotating IPs or server bans.

Avoid detection with our dynamic IP solutions. Perfect for continuous data scraping without interruptions.

Avoid Detection

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay