Is it allowed to modify value of the Value Object on construction

Viewed 85

Assuming that I want that following Value Object contains always capitalized String value. Is it eligible to do it like this with toUpperCase() in constructor?

class CapitalizedId(value: String) {
    val value: String = value.toUpperCase()
    // getters
    // equals and hashCode
}
2 Answers

In general, I do not see a problem of performing such a simple transformation in a value object's constructor. There should of course be no surprises for the user of a constructor but as the name CapitalizedId already tells you that whatever will be created will be capitalized there is no surprise, from my point of view. I also perform validity checks in constructors to ensure business invariants are adhered.

If you are worried to not perform operations in a constructor or if the operations and validations become too complex you can always provide factory methods instead (or in Kotlin using companion, I guess, not a Kotlin expert) containing all the heavy lifting (think of LocalDateTime.of()) and validation logic and use it somehow like this:

CapitalizedId.of("abc5464g"); 

Note: when implementing a factory method the constructor should be made private in such cases

Is it eligible to do it like this with toUpperCase() in constructor?

Yes, in the sense that what you end up with is still an expression of the ValueObject pattern.

It's not consistent with the idea that initializers should initialize, and not also include other responsibilities. See Misko Hevery 2008.

Will this specific implementation be an expensive mistake? Probably not

Related