Java – how to protect yourself from parameter misalignment
Suppose I have this important method:
int generateId(int clientCode,int dataVersion) { return clientCode * 2 + dataVersion % 2; }
Both parameters are int, so it's easy to call this method with the wrong parameters, such as generateid (dataversion, clientcode) It will be compiled and executed successfully But the generated ID will be completely wrong, which can cause serious problems
So my question is: is there any way to protect yourself from this parameter dislocation?
Now I can only think of changing it to an int wrapper class, such as:
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); } }
And call it with generateid (New clientcode (clientcode), new version (version)) Of course, it cannot guarantee complete protection, but at least it is more transparent in this way
Is there a better / other way?
Solution
Consider configuring your object through method chaining
configure().withDataVersion(dataVersion).withClientCode(clientCode).generateId();
Although it makes the configuration more verbose, it is also clearer to read
Dataversion and clientcode information can be moved into inner classes Configure () starts the inner class. Withdataversion (int) and withclientcode (int) are basically setters Generateid () will build and return your ID as it is today