reflective software development, as a service

Menu

value objects and “equality”

Today Corey Haines posted another great video interview with JB Rainsberger. This time the topic under discussion was Value Objects. Well worth a listen (go ahead, I’ll wait).

The main gist of the discussion was JB’s assertion that the distinguishing feature of Value Objects is that their equality depends on their state, as opposed to depending on their identity. Thus two 1-Leu notes are “equal” if and only if they have the same monetary value, even though they have different identities (for example, their serial numbers differ). JB then proceeded to extol the virtues of imbuing Value Objects with an equality function and I agree, but only up to a point.

I don’t doubt that creating a new Value Object class to wrap a primitive yields many benefits, and in many cases one of those benefits is to allow the writing of an equality operator for that new class, thereby simplifying much code. But right now, this week, I’m in the throes of a refactoring whose sole purpose is to allow the removal of such an equality operator, because two different views need to compare these values differently.

Going back to real money for a moment, suppose two people looked in their wallets and discovered they had the same amount of money. Does that make their wallets “equal”? I’d say it depends on who’s asking, and why; you might be comparing for total value, whereas I might compare for total number of notes, for example. It doesn’t really make sense for wallets to have an equality operator, and yet in many respects they are interchangeable Platonic values.

That’s a bit contrived, but I do think it’s generally the case that objects with a multi-dimensional value can have multiple valid “definitions” of equality — and that therefore, in such cases, equality is in the eye of the beholder. Does that invalidate JB’s argument? No, I don’t think so. The various kinds of “equality” of objects with a multi-dimensional value still satisfy his definition, and they are still value objects. I’m just being a pedant. Again.