wonders whether Data Transfer Objects (DTO, also known as value objects)
should have accessors or not:
The programmer was aghast. "DTOs are always made with private
variables and getters and setters!" he said. "Why?" I asked.
Rob argues that DTO’s should not have accessors but only public fields, which
should be the only way to access them:
In my view OO programs contain two kinds of entities: Objects and Data
Structures […] On the other hand there is no good reason to use getters and
setters in a data structure. A data structure is simply a packet of data,
While I agree with him about the distinction between Objects and Data Structures, the point that Rob
is missing is that it is quite common to start with a Data Structure and have it
evolve toward an Object as your code changes over time. This has happened
to me countless times and the few times where I gave in to the simplicity of
declaring my Data Structures with public fields cost me some time when I had to
change not only the said structure but all the calling code to use accessors and
constructors instead of direct access.
Another reason why you should always use accessors for your DTO’s is that of
When I am trying to get a value from an object, I don’t want
to have to think "mmmh… is Employee a DTO or an Object? I think it’s a
DTO so I’ll just write employee.firstName… oops, no, I forgot it’s an
Object now, so I have to use employee.getFirstName()".
Uniformity is crucial.
I already have enough to think when I
write my code, I don’t want to spend extra time second guessing myself or having to
browse the class I want to use before I can do something as simple as getting a