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!