For instance in main method I havesetFirstName()
and call the Contact class to do this.
In the contact class I know I should use:public String getName()
and then public void setFirstName(String name)
I know this is the right way to do that. But instead, I find that if i do:
public String setFirstName(String name)
{
return this.name=name;
}
this will also work and I don't need to use getName()
method.
Can anyone please help me out why is that? Is my accessor/mutator method correct?
It is the very idea of an accessor that it only reads but does not modify. That is a useful convention, because if done consistently it makes reasoning about some code you don't know a lot easier. Normally, you shouldn't have to expect weird side effects from something named
getX()
. It may be ok to do some lazy initialization, but it is clearer if such "lazy getters" are namedgetOrCreateX()
or similar to give the user a hint that the first use might take a bit longer/involve some expensive operation.A mutator that returns something may be useful, but it will help users of your class if you name it in a way that gives a hint about what it returns. Is it an error code or the previous value? People don't expect return values from something named
setX()
, so they will be surprised to see such a signature and have to look at the documentation of your class to see what it does.Summary: Always code as if someone else will have to take over your code any moment - don't do things that would be surprising. Even if you never hand your code to anyone else, your future self will thank you for picking names that explain what the method does.
Note: Your implementation of the setter is not very useful, as it always returns the new value you just passed in.