value object

{{Short description|Object that represents a simple entity whose equality is not based on identity}}

In computer science, a value object is a small object that represents a simple entity whose equality is not based on identity: i.e. two value objects are equal when they have the same value, not necessarily being the same object.{{cite web

|last=Fowler

|first=Martin

|url=http://martinfowler.com/eaaCatalog/valueObject.html

|title=Value Object

|work=Catalog of Patterns of Enterprise Application Architecture

|publisher=Martin Fowler (martinfowler.com)

|accessdate=17 July 2011

|authorlink=Martin Fowler (software engineer)

|year=2003}}{{cite web

|title=Value Object

|url=http://c2.com/cgi/wiki?ValueObject

|work=Portland Pattern Repository's Wiki

|publisher=Cunningham & Cunningham, Inc. (c2.com)

|accessdate=6 September 2012}}

Examples of value objects are objects representing an amount of money or a date range.

Being small, one can have multiple copies of the same value object that represent the same entity: it is often simpler to create a new object rather than rely on a single instance and use references to it.

Value objects should be immutable:{{cite web

|title=Value Object Should be Immutable

|url=http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable

|work=Portland Pattern Repository's Wiki

|publisher=Cunningham & Cunningham, Inc. (c2.com)

|accessdate=6 September 2012}} this is required for the implicit contract that two value objects created equal, should remain equal. It is also useful for value objects to be immutable, as client code cannot put the value object in an invalid state or introduce buggy behaviour after instantiation.{{cite web|last1=Burns|first1=Sam|title=The Value of a Value Object|url=http://sam-burns.co.uk/37/the-value-of-a-value-object/|archive-url=https://archive.today/20150419150922/http://sam-burns.co.uk/37/the-value-of-a-value-object/|url-status=usurped|archive-date=April 19, 2015|website=sam-burns.co.uk}}

Value objects are among the building blocks of DDD.

Implementation

Due to the nuances of various object-oriented programming languages, each has its own methods and patterns for implementing and using value objects.

= C# =

In C#, a class is a reference type while a struct (concept derived from the struct in C language) is a value type.{{cite web

|url=http://msdn.microsoft.com/en-us/library/ms173109.aspx

|title=Classes and Structs (C# Programming Guide)

|publisher=Microsoft Developer Network (msdn.microsoft.com)

|accessdate=5 September 2012

|year=2012}}

Hence an instance derived from a class definition is an object while an instance derived from a struct definition is said to be a value object (to be precise a struct can be made immutable to represent a value object declaring attributes as readonly{{cite web

|url=http://blogs.msdn.com/b/lucabol/archive/2007/12/24/creating-an-immutable-value-object-in-c-part-iii-using-a-struct.aspx

|title=Creating an immutable value object in C# - Part III - Using a struct

|publisher=Luca Bolognese's WebLog

|accessdate=7 September 2012

|year=2012}}).

The following procedure can be carried out to add value object properties to a C# class:

  1. Override the [https://docs.microsoft.com/en-us/dotnet/api/system.object.equals?view=netframework-4.7.2 {{code|code=Object.Equals}}] method to ensure the object is compared using business logic
  2. Operator overload the default behavior of {{code|code===}} and {{code|code=!=}} to use the {{code|Equals}} method.
  3. Override the [https://docs.microsoft.com/en-us/dotnet/api/system.object.gethashcode?view=netframework-4.7.2 {{code|code=Object.GetHashCode}}] method and ensure that the hash is same for the objects who have same equality.
  4. Make the class immutable{{Cite web|url=http://www.codeproject.com/Articles/1043301/Immutable-objects-in-Csharp|title=Immutable objects in C# - CodeProject|last=Koirala|first=Shivprasad|website=www.codeproject.com|access-date=2017-12-26}} by removing any property setters and only passing member values through the constructors.{{Cite web|url=https://www.codeproject.com/Articles/1046193/Value-Object-Design-Pattern-in-Csharp|title=Value Object Design Pattern in C#|last=koirala|first=Shivprasad|website=www.codeproject.com|access-date=2017-12-26}}

Example:

public record StreetAddress(string Street, string City);

or with a more verbose syntax:

public class StreetAddress

{

public StreetAddress(string street, string city)

{

Street = street;

City = city;

}

public string Street { get; }

public string City { get; }

}

=C++=

In C++, a value object can be built by overloading the assignment operator and using appropriate constness constraints on the fields (that will be evaluated once by the initializer list of the constructor) and on the methods of the class.

However, if the fields themselves are declared const (rather than use non-const fields while only exposing "getter" accessors), then it won't be possible to fully overwrite such a value object with another ({{code|object1 {{=}} object2}}).

=Python=

Python has data classes which provides equality testing and can be made immutable using the frozen parameter.{{cite web |title=dataclasses — Data Classes |url=https://docs.python.org/3/library/dataclasses.html |website=Python documentation |access-date=7 June 2023}}

from dataclasses import dataclass

@dataclass(frozen=True)

class StreetAddress:

"""Represents a street address."""

street: str

city: str

=Java=

Value objects are available since Java 14, as data records{{cite web |title=Records Come to Java |url=https://blogs.oracle.com/javamagazine/records-come-to-java |accessdate=13 April 2021}}

Unlike C# and C++, Java has no support for custom value types at the language level. Every custom type is a reference type, and therefore has identity and reference semantics,{{cite web|url=http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.1|title=Java Language Specification, chapter 4. Types, Values, and Variables|access-date=7 October 2015}} though extending support for custom value types is being considered.{{cite web|url=http://openjdk.java.net/jeps/169|title=JEP 169: Value Objects|access-date=7 October 2015}}

Java programmers therefore emulate value objects by creating immutable objects,{{cite web

|url=http://www.javapractices.com/topic/TopicAction.do?Id=29

|title=Immutable objects

|work=Collected Java Practices

|accessdate=5 September 2012

|year=2012}} because if the state of an object does not change, passing references is semantically equivalent to copying value objects.

A class can be made immutable by declaring all attributes blank final,hence assignable only in the constructors and declaring all attributes to be of immutable type (such as {{Tt|String}}, {{Tt|Integer}}, or any other type declared in accordance with these rules), not of mutable type such an {{mono|ArrayList}} or even a {{mono|Date}}. They should also define equals and hashCode to compare values rather than references.

The term "VALJO" (VALue Java Object) has been coined to refer to the stricter set of rules necessary for a correctly defined immutable value object.{{cite web

|url=http://blog.joda.org/2014/03/valjos-value-java-objects.html

|title=VALJOs - Value Java Objects

|accessdate=19 October 2014}}

public class StreetAddress {

public final String street;

public final String city;

public StreetAddress(String street, String city) {

this.street = street;

this.city = city;

}

public boolean equals(StreetAddress that) {

return getClass()==that.getClass() && street==that.street && city==that.city;

}

public int hashCode() {

return Objects.hash(street, city);

}

}

Java 14 :

public record StreetAddress (String street, String city) {}

=Kotlin=

data class StreetAddress(val street: String, val city: String)

In Kotlin, any class may have a constructor shortcut before the class body (if there is a body at all), which doubles as a declaration of fields and the assignation to those fields. Adding the `data` keyword causes the generation of implementations of `equals` and `hashCode` and the like.

See also

References