We have a big application which uses a lot of Strings
:
Unfortunately our developers are only human. Sometimes the String
values get mixed up when calling methods.
For example:
// this method
public void addProductToOrder(String order, String productname, String serialnumber);
// should be called like:
addProductToOrder(order, productname, serialnumber);
// but is sometimes mistakenly called as:
addProductToOrder(productname, serialnumber, order);
Switching 2 parameters is hard to detect when your method takes about 30 of these parameters. (Yes, it's one of those heavy business applications)
Sidenote: We wouldn't have this problem if we created our own class SerialNumber
which just acts as a wrapper around String
. But that seems so wrong.
Recently, I started to wonder if there is a way to detect mix-ups using custom annotations. After all, there are already annotations like Nullable
, NonNull
...
And this is not very different.
We would like to annotate our source code, for example like this:
public void addProductToOrder(@OrderReference String order, @ProductName String productname, @SerialNumber String serialnumber);
Next, we would like to find a way to make our IDE detect that 2 parameters were switched here.
@OrderReference String order = "ORDER_001";
@SerialNumber String sn = "0001-1213-007";
@ProductName String productname = "beer";
addProductToOrder(productname, serialnumber, order);
// should have been: addProductToOrder(order, productname, serialnumber);
We are using IntelliJ IDE. What is possible without writing IDE plugins ?
While you should go with ControlAltDel's comment as an ultimate solution, Intelij does have an inspection "Suspicious variable/parameter name combination" that might help. You can enter common parameter names and it will warn you if it thinks the local variables do not match.