Effective C++, 2E | Item 46: Prefer compile-time and link-time errors to runtime errors Back to Item 45: Know what functions C++ silently writes and calls. Continue to Item 47: Ensure that non-local static objects are initialized before they're used. Item 46: Prefer compile-time and link-time errors to runtime errors. Other than in the few situations that cause C++ to throw exceptions (e.g., running out of memory see Item 7), the notion of a runtime error is as foreign to C++ as it is to C. There's no detection of underflow, overflow, division by zero, no checking for array bounds violations, etc. Once your program gets past a compiler and linker, you're on your own there's no safety net of any consequence. Much as with skydiving, some people are exhilarated by this state of affairs, others are paralyzed with fear. The motivation behind the philosophy, of course, is efficiency: without runtime checks, programs are smaller and faster. There is a different way to approach things. Languages like Smalltalk and LISP generally detect fewer kinds of errors during compilation and linking, but they provide hefty runtime systems that catch errors during execution. Unlike C++, these languages are almost always interpreted, and you pay a performance penalty for the extra flexibility they offer. Never forget that you are programming in C++. Even if you find the Smalltalk/LISP philosophy appealing, put it out of your mind. There's a lot to be said for adhering to the party line, and in this case, that means eschewing runtime errors. Whenever you can, push the detection of an error back from runtime to link-time, or, ideally, to compile-time. Such a methodology pays dividends not only in terms of program size and speed, but also in terms of reliability. If your program gets through compilers and a linker without eliciting error messages, you may be confident there aren't any compiler- or linker-detectable errors in your program, period. (The other possibility, of course, is that there are bugs in your compilers or linkers, but let us not depress ourselves by admitting to such possibilities.) With runtime errors, the situation is very different. Just because your program doesn't generate any runtime errors during a particular run, how can you be sure it won't generate errors during a different run, when you do things in a different order, use different data, or run for a longer or shorter period of time? You can test your program until you're blue in the face, but you'll still never cover all the possibilities. As a result, detecting errors at runtime is simply less secure than is catching them during compilation or linking. Often, by making relatively minor changes to your design, you can catch during compilation what might otherwise be a runtime error. This frequently involves the addition of new types to the program. (See also Item M33.) For example, suppose you are writing a class to represent dates in time. Your first cut might look like this: class Date { public: Date(int day, int month, int year); ... }; If you were to implement this constructor, one of the problems you'd face would be that of sanity checking on the values for the day and the month. Let's see how you can eliminate the need to validate the value passed in for the month. One obvious approach is to employ an enumerated type instead of an integer: enum Month { Jan = 1, Feb = 2, ... , Nov = 11, Dec = 12 }; class Date { public: Date(int day, Month month, int year); ... }; Unfortunately, this doesn't buy you that much, because enums don't have to be initialized: Month m; Date d(22, m, 1857); // m is undefined As a result, the Date constructor would still have to validate the value of the month parameter. To achieve enough security to dispense with runtime checks, you've got to use a class to represent months, and you must ensure that only valid months are created: class Month { public: static const Month Jan() { return 1; } static const Month Feb() { return 2; } ... static const Month Dec() { return 12; } int asInt() const // for convenience, make { return monthNumber; } // it possible to convert // a Month to an int private: Month(int number): monthNumber(number) {} const int monthNumber; }; class Date { public: Date(int day, const Month& month, int year); ... }; Several aspects of this design combine to make it work the way it does. First, the Month constructor is private. This prevents clients from creating new months. The only ones available are those returned by Month's static member functions, plus copies thereof. Second, each Month object is const, so it can't be changed. (Otherwise the temptation to transform January into June might sometimes prove overwhelming, at least in northern latitudes.) Finally, the only way to get a Month object is by calling a function or by copying an existing Month (via the implicit Month copy constructor see Item 45). This makes it possible to use Month objects anywhere and anytime; there's no need to worry about accidently using one before it's been initialized. (Item 47 explains why this might otherwise be a problem.) Given these classes, it is all but impossible for a client to specify an invalid month. It would be completely impossible were it not for the following abomination: Month *pm; // define uninitialized ptr Date d(1, *pm, 1997); // arghhh! use it! However, this involves dereferencing an uninitialized pointer, the results of which are undefined. (See Item 3 for my feelings about undefined behavior.) Unfortunately, I know of no way to prevent or detect this kind of heresy. However, if we assume this never happens, or if we don't care how our software behaves if it does, the Date constructor can dispense with sanity checking on its Month parameter. On the other hand, the constructor must still check the day parameter for validity how many days hath September, April, June, and November? This Date example replaces runtime checks with compile-time checks. You may be wondering when it is possible to use link-time checks. In truth, not very often. C++ uses the linker to ensure that needed functions are defined exactly once (see Item 45 for a description of what it takes to "need" a function). It also uses the linker to ensure that static objects (see Item 47) are defined exactly once. You'll tend to use the linker in the same way. For example, Item 27 describes how the linker's checks can make it useful to deliberately avoid defining a function you explicitly declare. Now don't get carried away. It's impractical to eliminate the need for all runtime checking. Any program that accepts interactive input, for example, is likely to have to validate that input. Similarly, a class implementing arrays that perform bounds checking (see Item 18) is usually going to have to validate the array index against the bounds every time an array access is made. Nonetheless, shifting checks from runtime to compile- or link-time is always a worthwhile goal, and you should pursue that goal whenever it is practical. Your reward for doing so is programs that are smaller, faster, and more reliable. Back to Item 45: Know what functions C++ silently writes and calls. Continue to Item 47: Ensure that non-local static objects are initialized before they're used.