I would agree that this is a bad habbit althoug I always try to find alternatives to an if-else-statement.
My first attempt would be:
class Person {
private final int age;
/**
* Creates a new person with age 0.
*/
Person() {
age = 0;
}
/**
* Creates a new person with age
* @param age the age of the person. Must be <code>>0</code>
*/
Person(int age) {
assert age>0;
this.age = age;
}
}
My second attempt would constist of an interface and two classes:
/**
* Anything with an age.
*/
interface HasAge {
/**
* @return the age
*/
int getAge();
}
/**
* A Person has name, gender, address etc
*/
class Person {
}
/**
* A Person with a fixed age.
*/
class PersonWithAge extends Person implements HasAge{
private final int age;
PersonWithAge(int age) {
this.age = age;
}
@Override
public int getAge() {
return age;
}
}