menu

hjk41的日志

Avatar

Effective C++ 46: Prefer compile-time and link-time errors to runtime errors

The problem with runtime errors is that they are unpredictable. You may get no error while testing, but you are not sure whether your software will crash at the face of an important client.
Consider writing a Date class:

class Date {
public:
  Date(int day, int month, int year);
  ...
};


Here, we must check the values of the parameters so that they don't represent a date that doesn't exist. You might want to write like this:

Date::Date(int day, int month, int year){
    if(day<=0 || day >31
       || month<=0 || month>=12){
        cout<<"ERROR: invalid date value"<<endl;
        exit(1);
        // or you can throw an exception here
    }
    [i]do the initiation...[/i]
}


This code will generate a runtime error if you past an invalid value to the constructor of Date. However, we can do it this way:

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);
  ...
};

int main(int argc, char* argv[])
{
	Date d(10,Month::Jan(),1998);
	
	return 0;
}


Now we don't have to check the value of the parameter month, because it can only be generated through the static member functions of class Month.
Nevertheless, it's impractical to eliminate the need for all runtime errors. We still have to check the value of parameter day, whose range varies with month.

评论已关闭