Java – Public fields in a Data Transfer Object

coding-stylejava

In my years of programming I've often made classes that simply group a few variables with their setters and getters. I've seen these types of objects referred to as value objects, domain objects or model objects depending on the context in which they are used. The most fitting term for generic usage seems to be Data Transfer Object (DTO). This describes a POJO that only contains accessors and mutators.

I've just written one such object that contains about fifty fields used to set theme parameters on a chart. Now I'm wondering if instead of generating a hundred getters and setters I should just declare these fields as public. Doing so goes against everything my programming instincts tell me yet I can't deny that it would greatly increase my code's legibility and reduce the amount of boilerplate code in the class.

The only reason I can see not to use public fields would be if I needed to perform any sort of validation on these fields. If we assume that type validation is sufficient for my purposes, is using public fields in this scenario an acceptable break from object-oriented design? Will a public DTO perform better in large batch operations?

Best Solution

Most programmers will default to private fields with getters/setters without thinking about it. But like any cargo-cult thing, it's better to make a conscious decision.

The main reason for using a getter/setter combination instead of a public field is that you can change the definition. So, if your DTO is part of an interface between components, best to use getters. If you change the inner workings, you can adapt the getter to mimic the old behaviour and maintain compatibility.

Another reason is that you can make read-only fields. Often for DTOs, read-only and immutable is a good choice.

A third reason could be that your DTO needs to be a javabean because you intend to use it in some tool that requires it.

If none of these properties go for you, there's no reason not to use public fields.

Don't expect much of a performance difference though :)