Skip to content
On this page

Value Objects

Introduction

As Wikipedia puts it

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.


There are two main characteristics for value objects:

  • They have no identity
  • They are immutable

Martin Fowler explains ValueObject in perhaps one of the easiest to understand language with examples. It's a must-read!!

The abstract class ValueObject helps us create these immutable objects in a much simplified manner

Class Signature

ts
abstract class ValueObject<T extends ValueObjectType = string> implements Serializable {
  //
}
abstract class ValueObject<T extends ValueObjectType = string> implements Serializable {
  //
}

ValueObjectType

Refer types for more information

Default validations

These are the default validations in place but can be overridden

Value TypeValidation CheckException Thrown
anyis nullValueObjectCanNotBeNullException
anyis undefinedValueObjectCanNotBeNullException
stringis emptyValueObjectCanNotBeEmptyException
numberis NaNValueObjectIsNotANumberException
numberis infiniteValueObjectIsInfiniteException

Released under the MIT License.