Stephen White wrote:
>I have a OOP programming problem.
>
>Imagine I have to keep the sum of a list of numbers. I'd think "list of
>numbers, use an array". Now how could I make the Array class keep a sum
>of all its elements? In my imaginary application, the sum is going to be
>looked up a lot more than the list is going to be changed.
>
>My first thought would be "have an instance veriable to keep the sum".
>
>So I want to write something like:
>
>  class SumArray < Array
(snip)
>The problem is that just defining the []= operator wouldn't be enough.
>There isn't a single point in which a value gets set in an Array, so I
>have no place I can put a hook into when a value gets changed.
>
>Would I have to write a mirror class that intercepts all the places the
>values could be changed, like the initial value of an array, out of range
>array extensions, iterators, etc?

It depends on what you need. If you really need 
an Array class that supports everything that 
Array supports, plus sum, then I think you're 
stuck hooking everything.

However, if you just need an Array-like class 
that supports those methods that you need, then 
you can get away with a minimal approach. Instead 
of inheriting from Array, delegate to it. 

I haven't used the delegate pattern object 
described in the pickaxe book, so I'm not sure 
how well that would work. The other approach is 
simply to have your SumArray class contain an 
Array member variable.

As long as the client software restricts its 
activities to those methods that you have chosen 
to support, then it won't even be able to tell 
whether it is dealing with an Array or a SumArray 
(except for that handy sum function).

One other note: Think twice about the complexity 
of storing the sum. Personally, I would code it 
with the brute-force approach of summing on-the-
fly first. If, and only if a) the app becomes too 
slow, and b)  benchmark showed that the 
bottleneck was in Sum, would I optimize it.

Kevin