I’m new to Java after working for a few years in PHP and I’m trying to get an idea of some of the best practices and norms when working with Java.
I’m wondering if it makes sense to make a whole class to act as a custom type just to enforce a limit on the range of an integer argument?
For example:
class Person() {
private int age;
public Person(int age) {
if(age < 0) {
throw new IllegalArgumentException();
}
this.age = age;
}
public int getAge() {
return age;
}
}
Or:
class Person() {
private Age age;
public Person(Age age) {
this.age = age;
}
public int getAge() {
return age.toInt();
}
}
class Age() {
private int age;
public Age(int age) {
if(age < 0) {
throw new IllegalArgumentException();
}
this.age = age;
}
public toInt() {
return age;
}
}
Also, in the second example I’m converting the Age object to an int in Person.getAge(), which is convenient but somehow feels wrong since Person’s constructor takes an Age object. Any thoughts?
Thanks!
I think your second example is a bit overkill for this case, as you only have a single integer with a single constraint on it, and
Agedoes not have any behavior associated with it. If any of these were different, for instance, if you had more data with interrelated constraints, it might make sense to separate those into their own class. So your second design isn’t really wrong, just unsuitable for this toy example.For your second example, I would probably have the
Person.getAgemethod return anAgeobject instead of anint. Again, with this toy example it’s harder to see a difference, but returning anintfeels like a bit too much coupling betweenPersonandAge.