Main Content

Calculation within objects - early, last minute, or cached?

Archive - Originally posted on "The Horse's Mouth" - 2010-02-26 07:51:28 - Graham Ellis

When you create an object with the constructor, you may also set property [attribute] values within it ... or you may follow on with a series of method calls to set the initial values. Then when you pull back values / attributes / properties from your object you return those values, or the results of calculations on them.

Should you do the calculations at the time that you put the values into the object, or when you require to get them out?

In theory, the answer is it doesn't matter! ... the user of a class creates objects, calls values back, and lets the internals hide ("encapsulate") the storage and calculation. But in practise it CAN make a difference - in efficiency, for example, if there is significant calculation work involved in moving from the values put in to the results drawn out.

Lets look at the options

1. If you're creating a class in which you anticipate large numbers of objects being created, and with only a sparse readback of many of the more complex attributes, you'll be best advised to write the class so that the calculations are done "just in time" as results are called up

2. If, on the other hand, your class is likely to have a few objects created, but then the attributes will be called up many times over, you'll be best advised to do the calculations as the values are entered into the objects. And there's a third option ...

3. Just store the incoming attributes as they're entered, even if you expect them to be called back many times. When a result is called up for the first time, hold on to the result, and set a flag to say "we have the result already", then on subsequent requests for the same results you can short-circuit the calculation and just pass back the result.

If you're unsure about the "metrics" of your users and will have heavy computing involved, you'll be well advised to use the caching technique of option (3). Because your code is Object Oriented, you've got full control over all the methods used to access the data, so you can carefully set up your cached / stored flag to avoid problems with stale caches ... if your design is right, there will be no way of bypassing the methods that you've provided to ensure that the user's data access is robust.

We had a discussion on calculating early, or late, or caching on yesterday's Java Bootcamp Training Course and I've added a sample class that shows caching on our web site - source code [here].