|We don't bite newbies here... much|
Re^2: The fallacy of the *requirement* for read-only instance variables.by GotToBTru (Hermit)
|on Apr 20, 2011 at 06:47 UTC||Need Help??|
Okay, I added a comment on the root of this thread after it had gone on a while. Let me clarify a bit.
The premise of this thread was "under what conditions is it correct to use a read-only instance variable?" You said there were 3 conditions:
I'm suggesting that a unique id would be a counter example. Does it need to be read-only? Absolutely. The unique id is a property of a particular instance of a class that makes it distinguishable from all other instances. Read-only is relative of course. The object itself must be able to modify the value but nothing external should be able to. The value would be set at the time the object is instantiated. Is an instance variable an appropriate place to store this? Absolutely. The value must reside in the instance of the object. Two different instances will have different unique ids. And there is no need to supply a method, the values are static once set. Simply inspect the value.
I used the example of a "dog" class. It is easy to imagine another example: breed. The breed of dog would be set in the object at the time of creation and won't ever change during the life of the object.
The details of setting the unique id need not be expensive at all (increment a class variable by 1 for instance), but only the class itself has the knowledge to set it. Breed would probably be passed as a parameter to the constructor but again, not an expensive calculation any way you look at it. Also, the use of a read-only instance variable is dictated by the application - a value that can't be changed and is tightly associated with the instantiated object. I don't see how it possibly matters how many times it is used.
I don't see myself how a unique id would be used internally but I haven't worked out the implementation details. I mention this only for completeness. It was the third point and I can't speak to it.
I hope this clears up what I was saying.