I would like to mention another aspect which hasn't been mentioned by most others, and that's your constructor
public Employee(String, Date, String, Designation, double, Date)
The more arguments you add to a constructor, the harder it gets to use because the order of parameters isn't clear anymore. When you have multiple parameters of the same type, like in this case two String
s and two Date
s, it becomes very easy to mix them up which causes a bug which is hard to spot when reading the code.
A good way to handle this issue for immutable objects is to make the constructor private and call it from a Builder class which is a public class declared inside the class it builds (it needs to be inside to be able to call a private constructor).
Employee.Builder builder = new Employee.Builder();
builder.setName(name);
builder.setDateOfBirth(dateOfJoining);
builder.setEmployeeID(id);
builder.setDesignation(designation);
builder.setSalary(salary);
builder.setDateOfJoining(birthdate);
Person p = builder.build();
The builder collects all the attributes you set in private variables. When you call build()
, it calls the constructor of Employee
with the attributes set before and returns the result.
By the way, do you see the bug I have in the above code? Would you be able to spot it if I had called the constructor directly?
When you have each setter of the Employee.Builder
return this
, you can also use a very elegant syntax known as "fluent interface":
Person p = new Employee.Builder().setName(name)
.setDateOfBirth(birthdate)
.setEmployeeID(id)
.setDesignation(designation)
.setSalary(salary)
.setDateOfJoining(dateOfJoining)
.build();