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:
it is never possible to access another object’s private methods directly, even if the object is of the same class as the caller.
You can email me at geeks#stephen.viles.geek.nz (change # to @).
Copyright © Stephen Viles. You can share or adapt this material under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 New Zealand license. This site is built with nanoc and hosted by NearlyFreeSpeech.NET.