Which is better, Field or Property access, and why?
Or perhaps a better phrasing would be, what types of situation are better handled by using Field access rather than Property access and vica versa?
I'd appreciate some feedback on what access type people are using and why.
As a Java programmer my gut reaction is to go with property access, since it preserves the encapsulation. But in reality, persistence is always going to be tightly tied to the internal structure of my object, and I can't see that adding private getters or setters specifically for hibernate actually provides a lot of benefit.
There are some benefits I can see for using property access
- I can initialize some transient objects that are dependant on the data from hibernate. This is by far the most convincing use case I can come up with.
- When unexpected values are appearing, it's easier to debug if I can have a debug point on the setter method
- If I want to change the internal structure but not the schema, I can do so and do the data transformation in the getter and setter
The last two cases are particularly flimsy, but all these cases I'm thinking would be better handled by using field access in most cases and just using the @AccessType annotation to change the access to property for those few fields that need it.
On the other hand, there are some serious disadvantages to property access. First off
- More Code. Yes, any decent IDE can generate the getters and setters for me, but they're still a maintenance burden. They also clutter up the class making it harder to see at a glance where the actual logic is.
- When I want null checks or other such business logic in my setters or getters I almost always need two sets of accessors, a private set for hibernate to use without the logic, and a public set for real code to use. This is particularly annoying.
All of this leads me to think I should be using field access most of the time and just overriding it when I need some additional behaviour. But hibernate defaults to using property access which would indicate to me that the Hibernate team believe it's the best option.
Is there some major advantage of property access I'm missing? Or is it just a matter of preference and coding style?