Best practices for checking valid input in OO design?

What is the best practices for checking valid input in a Object Oriented design?

Consider the following simple example, where we have a class Person which takes as argument age, in its constructor.

1
2
3
4
5
6
7
8
class Person {
public:
    Person(int age) {
      mAge = age;
    }
private:
    int mAge;
}


Now assume that in my main program, I want the user to enter data, such as age, and from that I will instantiate a Person, example:

1
2
3
4
5
6
7
8
9
int main() {
   
   int age;
   cin >> age;
   // if (age < 0 )   write error to user
   Person p(age);

   return 0;
}


The question is then, where should one check for valid input? I see two options.

1) Check after reading input in main() method before creating a Person object.
2) Check inside the constructor and throw an Exception if input is invalid.

1
2
3
4
5
6
7
8
class Person {
public:
    Person(int age) {
      if(age < 0)
        throw new InvalidAgeException();
      mAge = age;
    }


What do you think is the best design? I see good benefits from letting the constructor handle all the checking of valid data, however that would force me to use a try/catch every time one instantiates the class.
Actually, yhe first thing you shoud so is use the right data type.

1
2
3
4
5
6
7
8
class Person {
public:
    Person(unsigned int age) {
      mAge = age;
    }
private:
    unsigned int mAge;
}


Now you can't pass a negative age to the object.

Then all you need to worry about is handling bad inputs.

Andy

Last edited on
It is a good idea to make constructor check invariants. If constructor cannot create working object, it should throw an exception.

Also it is a good idea to have basic sanity check in user input to dive user chance to fix error before it will be passed further into your program.
Topic archived. No new replies allowed.