Today I've seen the following pattern: you have an object A and an object B. Object B accepts a pointer to A at its constructor.
Once B is created, there's a method B.doCalc() that performs a calculation (internally using A's information). The result is obtained with method B.getResult().
In order to perform another calculation, A is modified, and B.doCalc() is called again.
What is your opinion on this choice ? I would have designed it differently, but I want to hear your voice.
Edit : note that my main objection is to modify A to have a different result from B, without touching B.
Although similar, I think that just this discipline expresses a much better feeling of what's going on. Instead of
a = new A a.whatever = 5 b = new B(a) b.doCalc() res = b.getResult() a.whatever = 6 b.doCalc() res = b.getResult()
You get the a pointer object from b itself.
a = new A a.whatever = 5 b = new B(a) b.doCalc() res = b.getResult() a = b.getAPointer() a.whatever = 6 b.doCalc() res = b.getResult()
because it makes more explicit the fact that a is taken from b and then modified. I still don't like it, though...
Edit 2 : one of the reasons why B accepts A at constructor is because it has to setup internal data for the calculation. These data
- depend on the nature of A
- they must be read from the disk, which may be slow
- B may be run many times on the same A, albeit slightly modified A. The nature of these changes would not invalidate B's internal data. We don't want to re-load the info every time doCalc() is invoked, nor run the risk to run a doCalc(a) with B's internal data being inconsistent with the submitted A.