Value object

Last updated

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. [1] [2]

Contents

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. [2]

Value objects should be immutable: [3] 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. [4]

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. [5] 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 [6] ).

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

  1. Override the Object.Equals method to ensure the object is compared using business logic
  2. Operator overload the default behavior of == and != to use the Equals method.
  3. Override the Object.GetHashCode method and ensure that the hash is same for the objects who have same equality.
  4. Make the class immutable [7] by removing any property setters and only passing member values through the constructors. [8]

Example:

publicrecordStreetAddress(stringStreet,stringCity);

or with a more verbose syntax:

publicclassStreetAddress{publicStreetAddress(stringstreet,stringcity){Street=street;City=city;}publicstringStreet{get;}publicstringCity{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 (object1 = object2).

Python

Python have data classes which provides equality testing and can be made immutable using the frozen parameter. [9]

fromdataclassesimportdataclass@dataclass(frozen=True)classStreetAddress:"""Represents a street address."""street:strcity:str

Java

Value objects are available since Java 14, as data records [10]

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, [11] though extending support for custom value types is being considered. [12]

Java programmers therefore emulate value objects by creating immutable objects, [13] 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, [14] and declaring all attributes to be of immutable type (such as String, Integer, or any other type declared in accordance with these rules), not of mutable type such an ArrayList or even a 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. [15]

publicclassStreetAddress{publicfinalStringstreet;publicfinalStringcity;publicStreetAddress(Stringstreet,Stringcity){this.street=street;this.city=city;}publicbooleanequals(StreetAddressthat){returngetClass()==that.getClass()&&street==that.street&&city==that.city;}publicinthashCode(){returnObjects.hash(street,city);}}

Java 14 :

publicrecordStreetAddress(Stringstreet,Stringcity){}

Kotlin

dataclassStreetAddress(valstreet:String,valcity: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

Related Research Articles

In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.

In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

In object-oriented (OO) and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created. In some cases, an object is considered immutable even if some internally used attributes change, but the object's state appears unchanging from an external point of view. For example, an object that uses memoization to cache the results of expensive computations could still be considered an immutable object.

In object-oriented programming such as is often used in C++ and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method that is dispatched dynamically. Virtual functions are an important part of (runtime) polymorphism in object-oriented programming (OOP). They allow for the execution of target functions that were not precisely identified at compile time.

In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax. In some languages, particularly C++, function objects are often called functors.

This article compares two programming languages: C# with Java. While the focus of this article is mainly the languages and their features, such a comparison will necessarily also consider some features of platforms and libraries. For a more detailed comparison of the platforms, see Comparison of the Java and .NET platforms.

In class-based, object-oriented programming, a constructor is a special type of function called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

In computer science, a mutator method is a method used to control changes to a variable. They are also widely known as setter methods. Often a setter is accompanied by a getter, which returns the value of the private member variable. They are also known collectively as accessors.

In some programming languages, const is a type qualifier, which indicates that the data is read-only. While this can be used to declare constants, const in the C family of languages differs from similar constructs in other languages in that it is part of the type, and thus has complicated behavior when combined with pointers, references, composite data types, and type-checking. In other languages, the data is not in a single memory location, but copied at compile time for each use. Languages which use it include C, C++, D, JavaScript, Julia, and Rust.

In the Java programming language, the final keyword is used in several contexts to define an entity that can only be assigned once.

In computer programming, an opaque pointer is a special case of an opaque data type, a data type declared to be a pointer to a record or data structure of some unspecified type.

<span class="mw-page-title-main">JavaScript syntax</span> Set of rules defining correctly structured programs

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

A class in C++ is a user-defined type or data structure declared with any of the keywords class, struct or union that has data and functions as its members whose access is governed by the three access specifiers private, protected or public. By default access to members of a C++ class declared with the keyword class is private. The private members are not accessible outside the class; they can be accessed only through member functions of the class. The public members form an interface to the class and are accessible outside the class.

C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by the publication year of the specification, though it was formerly named C++0x because it was expected to be published before 2010.

In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.

In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral (null) behavior. The null object design pattern, which describes the uses of such objects and their behavior, was first published as "Void Value" and later in the Pattern Languages of Program Design book series as "Null Object".

This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.

In computer programming, a constant is a value that is not altered by the program during normal execution. When associated with an identifier, a constant is said to be "named," although the terms "constant" and "named constant" are often used interchangeably. This is contrasted with a variable, which is an identifier with a value that can be changed during normal execution. To simplify, constants' values remains, while the values of variables varies, both hence their names. where as the constant variable of variation is the number that results two variables.

In C++ computer programming, copy elision refers to a compiler optimization technique that eliminates unnecessary copying of objects.

<span class="mw-page-title-main">Strongly typed identifier</span>

A strongly typed identifier is user-defined data type which serves as an identifier or key that is strongly typed. This is a solution to the "primitive obsession" code smell as mentioned by Martin Fowler. The data type should preferably be immutable if possible. It is common for implementations to handle equality testing, serialization and model binding.

References

  1. Fowler, Martin (2003). "Value Object". Catalog of Patterns of Enterprise Application Architecture. Martin Fowler (martinfowler.com). Retrieved 17 July 2011.
  2. 1 2 "Value Object". Portland Pattern Repository's Wiki. Cunningham & Cunningham, Inc. (c2.com). Retrieved 6 September 2012.
  3. "Value Object Should be Immutable". Portland Pattern Repository's Wiki. Cunningham & Cunningham, Inc. (c2.com). Retrieved 6 September 2012.
  4. Burns, Sam. "The Value of a Value Object". sam-burns.co.uk.
  5. "Classes and Structs (C# Programming Guide)". Microsoft Developer Network (msdn.microsoft.com). 2012. Retrieved 5 September 2012.
  6. "Creating an immutable value object in C# - Part III - Using a struct". Luca Bolognese's WebLog. 2012. Retrieved 7 September 2012.
  7. Koirala, Shivprasad. "Immutable objects in C# - CodeProject". www.codeproject.com. Retrieved 2017-12-26.
  8. koirala, Shivprasad. "Value Object Design Pattern in C#". www.codeproject.com. Retrieved 2017-12-26.
  9. "dataclasses — Data Classes". Python documentation. Retrieved 7 June 2023.
  10. "Records Come to Java" . Retrieved 13 April 2021.
  11. "Java Language Specification, chapter 4. Types, Values, and Variables" . Retrieved 7 October 2015.
  12. "JEP 169: Value Objects" . Retrieved 7 October 2015.
  13. "Immutable objects". Collected Java Practices. 2012. Retrieved 5 September 2012.
  14. hence assignable only in the constructors
  15. "VALJOs - Value Java Objects" . Retrieved 19 October 2014.