假设我有这个重要的方法:
int generateId(int clientCode, int dataVersion) {
return clientCode * 2 + dataVersion % 2;
}
两个参数都是
int
,所以很容易用错位的参数调用这个方法,比如 generateId(dataVersion, clientCode)
。它将成功编译和执行。但是生成的 id 会完全错误,这会导致严重的问题。所以,我的问题是:有没有办法保护自己免受这种参数错位的影响?
现在我只能想到将其更改为
int
包装类,例如:int generateId(@Nonnull ClientCode clientCode, @Nonnull Version version) {
return clientCode.getValue() * 2 + version.getValue() % 2;
}
static class IntWrapper<T> {
private final int value;
IntWrapper(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
static class ClientCode extends IntWrapper<ClientCode> {
ClientCode(int value) {
super(value);
}
}
static class Version extends IntWrapper<Version> {
Version(int value) {
super(value);
}
}
并使用
generateId(new ClientCode(clientCode), new Version(version))
调用它。当然,它不能保证完全保护,但至少这样更透明。有没有更好的/其他方式?
最佳答案
考虑像这样通过方法链配置您的对象
configure().withDataVersion(dataVersion).withClientCode(clientCode).generateId();
虽然它使配置更加冗长,但阅读起来也更清晰。
DataVersion 和 ClientCode-Information 可以移动到内部类中。
configure()
初始化内部类,withDataVersion(int)
和 withClientCode(int)
基本上都是setter。 generateId()
将像今天一样构建并返回您的 Id。关于java - 如何保护自己免受参数错位,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44842372/