Property Or Field Access?
May 15, 2005 – 16:11 | hibernate, javaHibernate supports access objects attributes through Java Bean accessor methods or direct field access through reflection. You can also supply your own PropertyAccessor implementation, but in this post I’ll leave that aside and focus on comparing the first two approaches.
So here are the pros of property access I can think of:
- It conforms to the OO encapsulation principle. This is also the reason that property access is the preferred strategy by the Hibernate team (as discussed in Hibernate In Action and implied by it being the default accessing strategy in mapping file definitions).
- It provides a subclass the possibility to override a property accessor.
- Field access assumes a SecurityManager not restricting access to private instance variables. In most of cases this is a valid assumption - if an application needs to worry about others running in the same JVM peeking into its private fields, it should probably get its own JVM. But still, property access does not have this kind of restriction.
Now the pros of field access:
- Field access allows to bypass an accessor that has more logic in it than simple value getting/setting. If we want to achieve direct mapping between database and domain objects (rather than DTOs), this can be very useful because most of the time the extra logic added is business logic, and should not or need not be applied at persistence time.
- Field access eliminates the need to define an accessor that does not make sense in the domain model, but just for the sake of populating the field at persistence time. The most typical example is the primary key field in every “Hibernated” objects, which usually should never be changed through out the object’s lifetime. From the architecture standpoint, this is also a strong argument for the field access approach because it prevents the leakage of concerns from the data access layer into the domain model.
