Part IV Object-OrientedProgramming 16_597043 pt04.qxd 9/20/05 2:03 PM Page 211 In this part . . . O bject-oriented programming is the most hyped term in the programming world — dot-com and business- to-business e-commerce eclipsed it for a year or two, but their high-flying fortunes have ’er, subsided, since the dot-com crash of 2001. C++ claims to be object-oriented — that’s what differenti- ated it from good ol’ C. Java is definitely object-oriented, as are a hundred or so other languages that were invented during the last ten years. But what is object-oriented? Do I have it? Can I get it? Do I want it? Part IV demonstrates the features of C# that make itobject-oriented to the core. Not only will you be program- ming objects, but you’ll also take possession of the keys to powerful, flexible program designs — all right here in Part IV! 16_597043 pt04.qxd 9/20/05 2:03 PM Page 212 Chapter 10 Object-OrientedProgramming — What’sItAll About? In This Chapter ᮣ Making nachos ᮣ Reviewing the basics of object-orientedprogramming ᮣ Getting a handle on abstraction and classification ᮣ Understanding why object-orientedprogramming is important T his chapter answers the musical question, “What are the concepts behind object-orientedprogramming and how do they differ from the functional concepts covered in Part II of this book?” Object-Oriented Concept #1 — Abstraction Sometimes when my son and I are watching football, I whip up a terribly unhealthy batch of nachos. I dump some chips on a plate; throw on some beans, cheese, and lots of jalapeños; and nuke the whole mess in the microwave oven for a few minutes. To use my microwave, I open the door, throw the stuff in, and punch a few buttons on the front. After a few minutes, the nachos are done. (I try not to stand in front of the microwave while it’s working lest my eyes start glowing in the dark.) 17_597043 ch10.qxd 9/20/05 2:04 PM Page 213 Now think for a minute aboutall the things I don’t do to use my microwave: ߜ I don’t rewire or change anything inside the microwave to get it to work. The microwave has an interface — the front panel with all the buttons and the little time display — that lets me do everything I need. ߜ I don’t have to reprogram the software used to drive the little processor inside my microwave, even if I cooked a different dish the last time I used the microwave. ߜ I don’t look inside my microwave’s case. ߜ Even if I were a microwave designer and knew allabout the inner work- ings of a microwave, including its software, I still wouldn’t think aboutall that stuff while I was using it to heat my nachos. These are not profound observations. You can deal with only so much stress in your life. To reduce the number of things that you deal with, you work at a certain level of detail. In object-oriented (OO) computerese, the level of detail at which you are working is called the level of abstraction. To introduce another OO term while I have the chance, I abstract away the details of the microwave’s innards. Happily, computer scientists — and thousands of geeks — have invented object orientation and numerous other concepts that reduce the level of complexity at which programmers have to work. Using powerful abstractions makes the job simpler and far less error-prone than it used to be. In a sense, that’s what the past half century or so of computing progress has been about: managing ever more complex concepts and structures with ever less errors. When I’m working on nachos, I view my microwave oven as a box. (As I’m trying to knock out a snack, I can’t worry about the innards of the microwave oven and still follow the Cowboys on the tube.) As long as I use the microwave only through its interface (the keypad), nothing I can do should cause the microwave to enter an inconsistent state and crash or, worse, turn my nachos — or my house — into a blackened, flaming mass. Preparing functional nachos Suppose I were to ask my son to write an algorithm for how Dad makes nachos. After he understood what I wanted, he would probably write, “Open a can of beans, grate some cheese, cut the jalapeños,” and so on. When he came to the part about microwaving the concoction, he would write some- thing like, “Cook in the microwave for five minutes” (on a good day). That description is straightforward and complete. But it’s not the way a func- tional programmer would code a program to make nachos. Functional pro- grammers live in a world devoid of objects such as microwave ovens and 214 Part IV: Object-OrientedProgramming 17_597043 ch10.qxd 9/20/05 2:04 PM Page 214 other appliances. They tend to worry about flow charts with their myriad functional paths. In a functional solution to the nachos problem, the flow of control would pass through my finger to the front panel and then to the inter- nals of the microwave. Pretty soon, flow would be wiggling around through complex logic paths about how long to turn on the microwave tube and whether to sound the “come and get it” tone. In that world of functional programming, you can’t easily think in terms of levels of abstraction. There are no objects and no abstractions behind which to hide inherent complexity. Preparing object-oriented nachos In an object-oriented approach to making nachos, I would first identify the types of objects in the problem: chips, beans, cheese, jalapeños, and an oven. Then, I would begin the task of modeling those objects in software, without regard for the details of how they will be used in the final program. For exam- ple, I can model cheese as an object pretty much in isolation from the other objects, and then combine it with the beans, the chips, the jalapeños, and the oven and make them interact. While I do that, I’m said to be working (and thinking) at the level of the basic objects. I need to think about making a useful oven, but I don’t have to think about the logical process of making nachos — yet. After all, the microwave designers didn’t think about the specific problem of my making a snack. Rather, they set about solving the problem of designing and building a useful microwave. After I have successfully coded and tested the objects I need, I can ratchet up to the next level of abstraction. I can start thinking at the nacho-making level, rather than the microwave-making level. At this point, I can pretty much translate my son’s instructions directly into C# code. Object-Oriented Concept #2 — Classification Critical to the concept of abstraction is that of classification. If I were to ask my son, “What’s a microwave?” he would probably say, “It’s an oven that. . . .” If I then asked, “What’s an oven?” he might reply, “It’s a kitchen appliance that. . . .” If I then asked “What’s a kitchen appliance?” he would probably say, “Why are you asking so many stupid questions?” 215 Chapter 10: Object-OrientedProgramming — What’sItAll About? 17_597043 ch10.qxd 9/20/05 2:04 PM Page 215 The answers my son gave in my example questioning stem from his under- standing of our particular microwave as an example of the type of things called microwave ovens. In addition, my son sees microwave ovens as just a special type of oven, which itself is just a special type of kitchen appliance. In object-oriented computerese, my microwave is an instance of the class microwave . The class microwave is a subclass of the class oven , and the class oven is a subclass of the class kitchen appliance . Humans classify. Everything about our world is ordered into taxonomies. We do this to reduce the number of things we have to remember. Take, for exam- ple, the first time you saw an SUV. The advertisement probably called the SUV “revolutionary, the likes of which have never been seen.” But you and I know that just isn’t so. I like the looks of some SUVs (others need to go back to take another crack at it), but hey, an SUV is a car. As such, it shares all (or at least most of) the properties of other cars. It has a steering wheel, seats, a motor, brakes, and so on. I bet I could even drive one without reading the user’s manual first. I don’t have to clutter my limited storage with all the things that an SUV has in common with other cars. All I have to remember is “an SUV is a car that . . .” and tack on those few things that are unique to an SUV (like the price tag). I can go further. Cars are a subclass of wheeled vehicles along with other mem- bers, such as trucks and pickups. Maybe wheeled vehicles are a subclass of vehicles, which include boats and planes — and so on. Why Classify? Why should you classify? It sounds like a lot of trouble. Besides, people have been using the functional approach for so long, so why change now? Designing and building a microwave oven specifically for this one problem may seem easier than building a separate, more generic oven object. Suppose, for example, that I want to build a microwave to cook nachos and nachos only. I would not need to put a front panel on it, other than a START button. I always cook nachos the same amount of time. I could dispense with all that DEFROST and TEMP COOK nonsense. The oven only needs to hold one flat little plate. Three cubic feet of space would be wasted on nachos. For that matter, I can dispense with the concept of “microwave oven” alto- gether. All I really need is the guts of the oven. Then, in the recipe, I put the instructions to make it work: “Put nachos in the box. Connect the red wire to 216 Part IV: Object-OrientedProgramming 17_597043 ch10.qxd 9/20/05 2:04 PM Page 216 the black wire. Bring the radar tube up to about 3,000 volts. Notice a slight hum. Try not to stand too close if you intend to have children.” Stuff like that. But the functional approach has the following problems: ߜ It’s too complex. I don’t want the details of oven building mixed into the details of nacho building. If I can’t define the objects and pull them out of the morass of details to deal with separately, I must deal with all the complexities of the problem at the same time. ߜ It’s not flexible. Someday, I may need to replace the microwave oven with some other type of oven. I should be able to do so as long as the two ovens have the same interface. Without being clearly delineated and developed separately, one object type can’t be cleanly removed and replaced with another. ߜ It’s not reusable. Ovens are used to make lots of different dishes. I don’t want to create a new oven every time I encounter a new recipe. Having solved a problem once, I’d like to be able to reuse the solution in other places within my program. If I’m really lucky, I may be able to reuse it in future programs as well. Object-Oriented Concept #3 — Usable Interfaces An object must be able to project an external interface that is sufficient but as simple as possible. This is sort of the reverse of Concept #4 (described in the next section). If the device interface is insufficient, users may start ripping the top off the device, in direct violation of the laws of God and Society — or at least the liability laws of the Great State of Texas. And believe me, you do not want to violate the laws of the Great State of Texas. On the flip side, if the device interface is too complex, no one will buy the device — or at least, no one will use all its features. People complain constantly that their VCRs are too complex (this is less of a problem with today’s on-screen controls). These devices have too many but- tons with too many different functions. Often, the same button has different functions, depending on the state of the machine. In addition, no two VCRs seem to have the same interface. For whatever reason, the VCR projects an interface that is too difficult and too nonstandard for most people to use. 217 Chapter 10: Object-OrientedProgramming — What’sItAll About? 17_597043 ch10.qxd 9/20/05 2:04 PM Page 217 Compare this with an automobile. It would be difficult to argue that a car is less complicated than a VCR. However, people don’t seem to have much trou- ble driving them. All automobiles offer more or less the same controls in more or less the same place. For example (this is a true story), my sister once had a car — need I say, a French car — with the headlight control on the left-hand side of the steering wheel, where the turn signal handle normally would be. You pushed down on the light lever to turn off the lights, and you raised the lever to turn them on. This may seem like a small difference, but I never did learn to turn left in that car at night without turning off the lights. Well-designed autos do not use the same control to perform more than one operation, depending on the state of the car. I can think of only one exception to this rule: Some buttons on most cruise controls are overloaded with multi- ple functions. Object-Oriented Concept #4 — Access Control A microwave oven must be built so that no combination of keystrokes that you can enter on the front keypad can cause the oven to hurt you. Certainly, some combinations don’t do anything. However, no sequence of keystrokes should do the following: ߜ Break the device: You may be able to put the device into some sort of strange state in which it won’t do anything until you reset it, like throw- ing an internal breaker. However, you shouldn’t be able to break the device by using the front panel — unless, of course, you throw it to the ground in frustration. The manufacturer of such a device would proba- bly have to send out some type of fix for a device like that. ߜ Cause the device to catch fire and burn down the house: Now, as bad as it may be for the device to break itself, catching fire is much worse. We live in a litigious society. The manufacturer’s corporate officers would likely end up in jail, especially if I have anything to say about it. However, to enforce these two rules, you have to take some responsibility. You can’t make modifications to the inside of the device. Almost all kitchen devices of any complexity, including microwave ovens, have a small seal to keep consumers from reaching inside the device. If that 218 Part IV: Object-OrientedProgramming 17_597043 ch10.qxd 9/20/05 2:04 PM Page 218 seal is broken, indicating that the cover of the device has been removed, the manufacturer no longer bears responsibility. If you modify the internals of an oven, you are responsible if it subsequently catches fire and burns down the house. Similarly, a class must be able to control access to its data members. No sequence of calls to class members should cause your program to crash. The class cannot possibly ensure this if external elements have access to the internal state of the class. The class must be able to keep critical data mem- bers inaccessible to the outside world. How Does C# Support Object-Oriented Concepts? Okay, how does C# implement object-oriented programming? In a sense, this is the wrong question. C# is an object-oriented language; however, it doesn’t implement object-orientedprogramming — the programmer does. You can certainly write a non-object-oriented program in C# or any other language (by, for instance, writing all of Microsoft Word in Main() ). Something like “you can lead a horse to water” comes to mind. But you can easily write an object-oriented program in C#. C# provides the following features necessary for writing object-oriented programs: ߜ Controlled access: C# controls the way in which members can be accessed. C# keywords enable you to declare some members wide open to the public while internal members are protected from view and some secrets are kept private . Notice the little hints. Access control secrets are revealed in Chapter 11. ߜ Specialization: C# supports specialization through a mechanism known as class inheritance. One class inherits the members of another class. For example, you can create a Car class as a particular type of Vehicle . Chapter 12 specializes in specialization. ߜ Polymorphism: This feature enables an object to perform an operation the way it wants to. The Rocket type of Vehicle may implement the Start operation much differently from the way the Car type of Vehicle does. At least, I hope it does every time I turn the key in my car — with my car you never know. Chapters 13 and 14 find their own way of describing polymorphism. 219 Chapter 10: Object-OrientedProgramming — What’sItAll About? 17_597043 ch10.qxd 9/20/05 2:04 PM Page 219 220 Part IV: Object-OrientedProgramming 17_597043 ch10.qxd 9/20/05 2:04 PM Page 220 . 212 Chapter 10 Object-Oriented Programming — What’s It All About? In This Chapter ᮣ Making nachos ᮣ Reviewing the basics of object-oriented programming ᮣ. is an object-oriented language; however, it doesn’t implement object-oriented programming — the programmer does. You can certainly write a non-object-oriented