Narrowing Your Focus
It's easy to get wrapped up in writing code and make a class do too much. If we started adding coffee makers and paper shredders to our car class, that would be silly. These functions are not essential to the basic functionality that we need from a car. Not only that, but if we wanted to make coffee in some other context, we would need the entire car. Can you imagine a car in your kitchen?Speaking of kitchens, the point is that you shouldn't include the kitchen sink in your class design. A class should do one fairly simple thing. When we're designing a class and considering what it should include, we want it to be simple. Code reuse is certainly an important consideration, but keeping your code organized and easy to maintain is another reason to narrow the scope of the class.This is not to say that classes should be limited to a few dozen lines of code that deal with the most primitive objects possible. A VendingMachine class would serve one important function, namely dispensing soda, but it would do a great many things with different objects. It would dispense SodaBottle objects, accept Coin objects, give Coin objects back for change, scroll a promotional message across its LedDisplay, and so on.That same VendingMachine should not, however, do things that aren't important to dispensing soda. It should not make phone calls to the distributor (actually, some machines might already do this, but don't start making exceptions!), it should not be an automated teller machine, it shouldn't be a bottle opener (that would be its own class because beer bottles need to be opened as well), and it shouldn't drink the soda for you.
Maybe our vending machine doesn't call headquarters, but the beauty of object-oriented programming is that someone else could inherit our VendingMachine class and add that functionality. |