Re:Ask HN: Why do you make class members private?
by Jtsummers on Monday July 25, 2022 @04:05PM
(#32230200)
Invalid state means invalid state. Suppose (going with my bounded stack example from another reply to you) you initialize the stack with:
There are various actions applied, correctly, through the interface (push, pop, and peek). Somewhere, you decide to manually alter the size of the stack but not through its interface (resize)
But you forget (someone came by with cookies) to actually shrink the backing array and also to change "top". So now you end up with this state:
Oops, top is not allowed to be larger than limit, and array.size is supposed to be equal to limit. That is an invalid state, people can still use the public interface (push, pop, peek), but who knows what they'll get back.
[ Parent
| on HN ]
Re:Ask HN: Why do you make class members private?
by robalni on Tuesday July 26, 2022 @03:34AM
(#32235428)
> But you forget (someone came by with cookies) to actually shrink the backing array and also to change "top".
Someone could come by with cookies while I'm writing a private function too. This is more of a reason for having a function for doing something. Is the reason to make those variables private then to tell the programmer that there is a function that changes them and that you have to look through all the functions of the class before you touch them to see if there is a function that does what you need?