I'm learning the concept of implementing comparable
and comparator
interface to my own class and I saw the statement below from Java tutorial oracle regarding to the best practice of implementing comparable
and comparator
interface:
The constructor checks its arguments for null. This ensures that all Name objects are well formed so that none of the other methods will ever throw a NullPointerException.
I'm trying to create an Employee
class with int id, int salary, int age, String name
and Date dateOfJoining
as instance variables. I know that primitive type such as int can't equal to null, but what should I do to check whether int variables are well formed or not?
public class Employee implements Comparable<Employee>{
public static void main(String[] args) {
}
private int id;
private String name;
private int salary;
private int age;
private Date dateOfJoining;
//how to check whether int varaibles are well formed or not?
public Employee(int id, String name, int salary, int age, Date dateOfJoining){
this.id = id;
this.name = name;
this.salary = salary;
this.age = age;
this.dateOfJoining = dateOfJoining;
}
@Override
public int compareTo(Employee o) {
// to be implemented
}
}
The tutorial that you referred to is the Object Ordering tutorial. The particular statement referred to the Name
class that is given there as an example: If you created such a Name
object where the firstName
or the lastName
object was null
, then the compareTo
method would throw a NullPointerException
. This is prevented by checking the constructor arguments immediately.
More generally speaking, you should make sure that the compareTo
method can not throw any exception.
As you already noticed, there is no way in which an int
variable can be "malformed" in this sense. It can not be null
, and no exception can be caused by comparing an int
value to another.
However, there are several other points listed in the tutorial, and which you should take care of:
hashCode
equals
compareTo
is consistent with equals, as described in the Comparable
documentationfinal
so that the class is immutableA hint: You can use the Integer#compare
method to compare int values conveniently.
A side note: Keep in mind that although an int
value is always "well formed" in a technical sense, there certainly are business constraints that should be checked in the constructor. In your example, you'd likely want to insert additional sanity checks for some of the fields in the constructor:
public Employee(int id, String name, int salary, int age, Date dateOfJoining){
this.id = id;
this.name = Objects.requireNonNull(name);
if (salary <= 0) {
throw new IllegalArgumentException(
"The salary should be positive, but is "+salary);
}
this.salary = salary;
if (age <= 0) {
throw new IllegalArgumentException(
"The age should be positive, but is "+salary);
}
this.age = age;
this.dateOfJoining = Objects.requireNonNull(dateOfJoining);
}