Switch statements indicate polymorphism

Any time you find yourself writing code that looks like "If it's an A, do this; if it's a B, do that; if it's a C...," reconsider your design. If A, B, and C all have a common base class, that base class needs a virtual function that each subclass can override. You then call that virtual function instead of your switch statement.

This applies even when you're trying to create an object. If you have a set of objects, and you want to create an object that corresponds to an object in that set, ask the first object to create the new object. The alternative--testing the object type and creating the second object on that basis--is not extensible when new types of objects are introduced.

Consider video device configuration. Different video devices have different capabilities. For this reason, the user interface for configuring a video device is highly device dependent. Some devices are not frame buffers; to those, concepts like bit depth are meaningless. Rather than query the device to figure out what kind of user interface to use ("Are you a frame buffer? How many bit depths do you have?"), have the video device return a user interface object via a virtual member function. The function can even return an object that can later create that user interface object--a reference surrogate. For more information, see "Surrogate objects" on page 121.

This does not imply that every video device must implement its own user interface. If most devices have common characteristics, Taligent might provide a standard user interface object for most devices to return. This way you can handle devices with special requirements without having to revise the system to know about them.

NOTE Classes used at boot time must be careful about referring to classes that, in turn, refer to things in high-level shared libraries. Using indirect reference objects alleviates that problem.

[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker