Skip to main content
2 of 3
added 122 characters in body
Philipp
  • 221
  • 1
  • 5

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 Strings and two Dates, 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();
Philipp
  • 221
  • 1
  • 5