3 Keeping objects consistent
This chapter covers
- Keeping classes consistent
- Emerging problems with inconsistent objects
- Implementing pre-conditions and business validation mechanisms
A well-designed class encapsulates all its data and offers clients operations that either give a sneak peek at the data or manipulate them. These operations, when properly designed, make sure that the object is always in a valid state and that there are no inconsistencies. Better yet, they do so in a way that the clients of the class don’t even need to know about it.
Suppose a class that implements a shopping cart. Regardless of how many items the user adds or removes from it, the total amount to pay should match the price of each item times its quantity. Or, if the user removed the item from the cart, that item should be removed completely, and there shouldn’t be an item with quantity zero. These are just a few examples of what I mean by keeping state and consistency in the title of this chapter.