as you can see the class below declares 2 private instance variables and 2 get & 2 set methods associated with each private member to allow for manipulation and validation of them.
My question is: which is better to use in the constructor deceleration, the instance variables directly as shown in the snippet below or to use the set methods associated with them and also which is promote good software practices to use in the toString method, the instance variables or their getter methods?
thank you for your time.
public Class Employee {
private String firstName;
private String lastName;
public Employee (String first, String last)
{
firstName = first;
lastName = last;
}//end of constructor
public void setFirstName(String first)
{
firstName = first;
}//end of method setFirstName
public String getFirstName()
{
return firstName;
}
public void setLastName(String last)
{
lastName = last;
}//end of method setLastName
public String getLastName()
{
return lastName;
}//end of method getLastName
public String toString()
{
return String.format ("%s: %s %s\n", "Employee Name: ", firstName, lastName);
}//end of method toString
}//end of class Employee
I tend to favour initialisation via construction. By using this method and providing appropriate checks (compilation time via final and runtime via null checks or similar) you can ensure your object is properly and completely instantiated.
Using the final keyword on your fields will make the compiler check that you've assigned a value to that field upon construction. It does mean that field is immutable, but it's surprising how often you require that.
I would be careful with providing getters for everything. If you're continually providing and using getters, that suggests that you're pulling data out of your object and manipulating it outside that object. Remember - a key principle of OO is getting objects to do things for you, rather than asking them for data and doing it yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With