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.