Hibernate trap: Do not directly access fields in another entity instance

Hibernate is great, but about once a year we get bitten by using it incorrectly. Latest lesson:

Don’t directly access fields on any instance other than ‘this’. Use the appropriate getter instead. So instead of:

public void aggregateQuantity(Trade other)
{
    quantity += other.quantity;
}

use:

public void aggregateQuantity(Trade other)
{
    quantity += other.getQuantity();
}

Why? Because the other entity instance may be an uninitialized proxy and you’ll get the default value for the type (null, zero or false), not the value you are expecting.

Hibernate gives you this particular reason to not access fields on another instance, but it’s generally bad form anyway. Just being the same class as another object should not give you the right to bypass its code. The Ruby programming language gets this right. From “Access Control (classes)” in the Programming Ruby online book:

it is never possible to access another object’s private methods directly, even if the object is of the same class as the caller.

Published 6 February 2009, tags: ,

Comments

You can email me at stephen#viles.nz (change # to @) or tweet me at @svilesnz.

Articles