Value Objects

Value Objects help us define semi-complex, identity-less objects without us needing to resort to spaghetti code.
Illustration from Undraw
TL;DR
Value Objects are like non-unique Entities. You use them in much the same way, except they bear no own identity. An instance of a Value Object is equivalent to another instance if they have the same properties and values. They are excellent for containing complex creational logic and work well when combined on Entities that contain Value Objects as part of their data.
Value Objects reside in the Domain layer.
Value objects are a Godsend.
Value objects are defined by attributes, not by identity. This makes them great for cases where you want to provide a "vending machine" for non-trivial objects, such as in our case, a TimeSlot. The TimeSlot itself has no identity, but it does have unique values in non-unique keys/attributes. Because this type of object needs to always be correctly constructed, we can delegate the responsibility into (for example) a class that creates such TimeSlots. You don't pass around Value Objects that much, nor update them. Instead, you instantiate new ones—they are 100% replaceable and interchangeable, after all!
This pattern is effective in refactoring, such as when wanting to cut down on primitive obsession.
Producing non-entity objects might invite one to use "easy" and regressive patterns fished out of the recesses of one's memory bank. "These aren't important!" Wrong.

Creating a TimeSlot as a Value Object

If there is something I know I need to build more often, it's Value Objects.
Get-A-Room doesn't have very many Value Objects (two, in fact). Let's look at the TimeSlot. This is how it's used:
code/Reservation/SlotReservation/src/domain/aggregates/Slot.ts
1
const timeSlot = new TimeSlot();
2
const currentTime = this.getCurrentTime();
3
4
for (let slotCount = 0; slotCount < numberHours; slotCount++) {
5
const hour = startHour + slotCount;
6
timeSlot.startingAt(hour);
7
const { startTime, endTime } = timeSlot.get();
8
const newSlot = this.makeSlot({ currentTime, startTime, endTime });
9
slots.push(newSlot);
10
}
And the Value Object itself:
code/Reservation/SlotReservation/src/domain/valueObjects/TimeSlot.ts
1
import { TimeSlotDTO } from "../../interfaces/TimeSlot";
2
3
import { InvalidHourCountError } from "../../application/errors/InvalidHourCountError";
4
5
/**
6
* @description Handles the creation of valid time objects.
7
*/
8
export class TimeSlot {
9
private startTime = "";
10
private endTime = "";
11
12
/**
13
* @description Creates a valid time object. Requires an `hour` provided as
14
* a number as input for the starting hour. Assumes 24 hour clock.
15
*
16
* All time slots are 1 hour long and provided as ISO strings.
17
* @example ```
18
* const timeSlot = new TimeSlot();
19
* timeSlot.startingAt(8);
20
* ```
21
*/
22
public startingAt(hour: number): void {
23
if (hour > 24) throw new InvalidHourCountError();
24
if (hour <= 0) hour = 0;
25
26
const startHour = hour.toString().length === 1 ? `0${hour}` : `${hour}`;
27
const endHour =
28
(hour + 1).toString().length === 1 ? `0${hour + 1}` : `${hour + 1}`;
29
const day = new Date(Date.now()).toISOString().substring(0, 10);
30
const startTime = new Date(`${day}T${startHour}:00:00`).toISOString();
31
const endTime = new Date(`${day}T${endHour}:00:00`).toISOString();
32
33
this.startTime = startTime;
34
this.endTime = endTime;
35
}
36
37
/**
38
* @description Returns a `TimeSlotDTO` for the start and end time.
39
*/
40
public get(): TimeSlotDTO {
41
return {
42
startTime: this.startTime,
43
endTime: this.endTime,
44
};
45
}
46
}
To save on memory we are reusing the same TimeSlot instance and calling it several times throughout the loop. This is probably not the right way to do it in certain circumstances, but here I feel it makes sense as we are never relying on the instance of the Value Object itself, just asking it to return a Data Transfer Object based on the input data. Perhaps this can be seen as acceptable in the limited range of uses that we get to use TimeSlot for.
On the plus side, we are neatly encapsulating a lot of tedious detail out of the actual usage contexts. This also ensures that validation is done and that the integrity is correct and can be trusted; You'll see the error handling if we receive an hour count over 24, and how we are resetting any zero values to an acceptable base.
It should be clear that Value Objects can be as simple or complex as possible. Use them whenever you feel that unique data types or values need to be addressed in a controlled manner.