The Value of Value Objects 💊

Value objects are identified by the immutable value they carry, are always valid, can have logic, and portray domain meaning. Let’s explore those characteristics.

Luís Soares
CodeX

--

Carry a value

Value objects represent domain concepts. They can be:

  • Mathematical values — represent coordinates on a continuous scale. e.g., Percentage, Money, Temperature, Point, Color, Date, Date Range, and Distance.
  • Identifiers — discrete values used to identify some entity. e.g., Email, Locale, Currency, Telephone number, IP address, URL, File path, and Product identifier (enums behave as identifiers, but they’re limited to a hardcoded set of values).

Usually, a value object holds a single primitive value [🚀], but it can have more. For example, an RGBA color holds four integers; a 3D point holds three numbers.

// The literal value is kept inside the value object
data class Email(val value: String)

fun main() {
val newEmail = Email("x@email.com")
assert("x@email.com" == newEmail.value)
}

Value objects don’t make sense on their own. They exist in the context of an entity. You might create a new one to run a findByEmail, for example, but other than that…

--

--

Luís Soares
CodeX
Writer for

I write about automated testing, Lean, TDD, CI/CD, trunk-based dev., user-centric dev, domain-centric arch, coding good practices,