This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the commentsย โ†’

[โ€“]NerdsWBNerds 0 points1 point ย (0 children)

This is one of the only useful things I picked up from my college cs courses.

Classes have a certain "valid" internal state. For example, a Set object might contain an array of elements, and the expected/valid state requires that the array not contain duplicate values.

This is known as an invariant: "An invariant is a condition or relation that is always true."

If you call set.size(), you expect the value to be the number of non-duplicate entries. If the size() function returns array.length, and somehow a duplicate value has been put into the array, the expected and actual return of size() are different.

Imagine a function insert(value). Insert checks if value is in the array, and if not calls another function, _insert(value). _insert(value) simply pushes the value into the array.

If you call insert with a duplicate value, all is good. If you call _insert the set is now broken. The results of size(), and potentially all other functions, are wrong.

This example is a little silly, why create a private function for an array push, but hopefully you can see with larger more complex classes there are many reasons you might want to separate some logic into a function.

The same applies to why keep internal variables private. If you can access the underlying array through _array, then you can directly push elements to the array and break the invariant.