I have a class say Test.java and it includes a member variable called errorCode which belongs to the class ErrorCode which is nothing but a wrapper over a int errorCode … My question is about the setter and getters, what should be the ideal signature for them. The errorCode is an int so the setter would be something like
class Test{
ErrorCode errorCode;
public void setCode(int errorCode)
{
this.errorCode = new ErrorCode(errorCode);
}
public int getCode()
{
return this.errorCode.getCode();
}
}
So should, the class create the object and let the client pass in an int or should the client create the object and class only set it to its member variable, ideally should we favor the client or the class ?
I’d say that, if at all possible, you should set things up so that your Test class doesn’t need to know what the internals of ErrorCode are. Right now it’s a wrapper around an int, but perhaps in the future it will need to be something else, or you may have multiple subclasses of ErrorCode.
Better for Test to accept and return ErrorCode objects, and let ErrorCode itself handle creating instances. You may want to give ErrorCode some static factory methods such as