Java Class ideal responsibilities with client
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
static ErrorCode createFromInt(int code) {
return new ErrorCode(code);
}
If you want your class to be a proper java bean, and you have a property ErrorCode errorCode
, then the convention is to have a setter and a getter of the form
public void setErrorCode(ErrorCode errorCode) {
this.errorCode = errorCode;
}
public ErrorCode getErrorCode(){...}
If you want to be able to set the error code by its underlying int
value, I would create a method
public void setErrorCodeByValue(int code) {
...
}
and you code do something similar to get just the code value of the ErrorCode
.
Note that you could define a method like
public void setErrorCode(int code) {...}
in addition to the proper Java bean setter shown above (so have 2 methods setErrorCode
, with different arguments, one of type ErrorCode
and one of type int
) if you want...
精彩评论