Value Object

from Wikipedia, the free encyclopedia

The Value Object (also value object ) is employed in software development design patterns . Value objects are unchangeable objects that represent a special value. If the value is to be changed, a new object must be generated. The design pattern is used to relate object comparisons to their attribute values ​​rather than object identity.

Explanation

For special values ​​it can make sense to use them as objects of their own class. This design pattern is often used, for example, for amounts of money or dates. With these more complex data types, the respective classes can be given their own methods and properties right from the start, which simplify later work with the value object.

According to Eric Evans' definition, objects of value have three fundamental properties:

  • Objects of value have no identity
  • Objects of value cannot be changed
  • Value objects are always created in a valid state

Examples

date

The "Date" class has the "getYear ()" and "getEuropeanDate ()" methods - these facilitate the handling of objects of the "Date" type.

Example (Java)

  • Value object class Money
import java.math.BigDecimal;
import java.util.Currency;
import java.util.Objects;

public final class Money {
	private final BigDecimal amount;
	private final Currency currency;

	public Money(BigDecimal amount, Currency currency) {
		Objects.requireNonNull(amount, "amount should be not null");
		Objects.requireNonNull(currency, "currency should be not null");
		this.amount = amount;
		this.currency = currency;
	}
	public BigDecimal getAmount() {
		return this.amount;
	}
	public Currency getCurrency() {
		return this.currency;
	}
	public Money add(Money other) {
		if (other == null || other.currency != currency) throw new IllegalArgumentException("Can't add " + other);
		return new Money(amount.add(other.amount), currency);
	}
	@Override
	public boolean equals(Object obj) {
		if (obj == null || getClass() != obj.getClass())
			return false;
		Money other = (Money) obj;
		return amount.equals(other.amount) && currency.equals(other.currency);
	}
}

Web links

Individual evidence

  1. 4.4 Classes of values ​​and classes of objects. Rheinwerk Computing - practical book on object orientation; accessed on August 31, 2015
  2. ^ Karl Eilebrecht, Gernot Starke: Patterns compact . 4th edition. Springer Vieweg Verlag, Berlin 2013, ISBN 978-3-642-34717-7 , p. 195-197 .
  3. heise.de - Compliance with invariants with the Value Object Pattern.Retrieved on March 28, 2016.