Immutability

An immutable object, is an object that cannot change its own state after its creation. This is true in object oriented and functional programming. The opposite, is a mutable object, that can change state. In DDD an entity is mutable, a value object are not. By definition must not change the state. I also prefer a dogmatic approach creating always a new object.

Create a value object on php

class MyImmutableObject
{
  public function withNamedConstructor()
  {
    return new self();
  }
}

And to always keep the control of object creation, I also keep constructor private. This constraint allow object creation only via factory methods. I love this kind of approach because allow a complete control of creation.

Java String is immutable

Indeed, in Java immutability is part of String objects behavior. Here an example. This means that every times we change the value of a string, object will not change: a new one created and returned.

class SomeExample {
  public static void main(String[] args) {
    String imm = "foo";
    System.out.println("Address: " + imm.hashCode());
    imm = "bar";
    System.out.println("Address: " + imm.hashCode());
  }
}

This will output:

Address: 42
Address: 2345

No one can mutate an immutable value. Thus, no one can change immutable string. And this is the reason why address are different for both objects.

results matching ""

    No results matching ""