13 Nov 2023



Intermediate

Value objects: Value objects are typically immutable objects(meaning that they cannot be changed once they are created). They do not have a unique identity. Value objects are often used to model quantities, dimensions, and other characteristics of entities.

Here's a simple breakdown:

  • Immutability: Once created, their state doesn't change. If you need to alter the value, you create a new object.
  • Attributes: Their identity is based on their attributes. For example, a "Date" value object is made of day, month, and year attributes.
  • Self-contained: They encapsulate their own logic and are typically used within entities to represent attributes or characteristics.

For instance, consider a "Money" value object representing an amount:

public class Money {
    private final int dollars;
    private final int cents;

    public Money(int dollars, int cents) {
        this.dollars = dollars;
        this.cents = cents;
    }

    // Other methods to work with money...
}

This "Money" value object bundles dollar and cent values, ensuring that any operation involving money remains consistent and doesn’t directly modify its state. This immutability and self-containment help keep things clear and manageable within the domain's logic.

Let's consider another example of a value object, such as a EmailAddress that represents an email address in a system:

public class EmailAddress {
    private final String address;

    public EmailAddress(String address) {
        // Perform validation if needed
        this.address = address;
    }

    public String getAddress() {
        return address;
    }

    // Other methods related to email address validation or operations...
}

In this example, the "EmailAddress" value object represents an email address. It has a single attribute, the address, and it's immutable once created. The constructor can include validation logic to ensure the provided address follows the rules of a valid email address.

This "EmailAddress" value object encapsulates the email-related logic, making it easy to use within entities or other parts of the domain model. It ensures that the email address is always in a valid and consistent state. If you need to change the email address, you would create a new "EmailAddress" object with the updated value.

More examples of value objects:

  • Money
  • Date
  • Address
  • Email address
  • Phone number
  • Quantity
  • Dimensions
  • Weight
  • Color
  • Location