Consider the following (imaginary) code extract:
class X {
private static String IS_PAYLOAD_REQUIRED = "4001";
[....]
checkPayloadRequired(String input) {
if (input.startsWith(IS_PAYLOAD_REQUIRED)) {
settings.enable(Integer.valueOf(IS_PAYLOAD_REQUIRED).intValue());
}
}
}
IS_PAYLOAD_REQUIRED
is required both as a String
and an int
. The code above delares a String
constant and converts to int
at runtime when necessary. This conversion is cheap but unnecessary.
Is it worth trying to avoid the conversion? I can think of the following two ways of doing it. Appreciate any comments on usefulness of either.
1: Declare Two variables
private static String IS_PAYLOAD_REQUIRED = "4001";
private static String IS_PAYLOAD_REQUIRED_INT = Integer.valueOf(IS_PAYLOAD_REQUIRED).intValue();
Now use one of the two constants.
2: Create a StringAndInt class private static StringAnInt IS_PAYLOAD_REQUIRED = new StringAnInt(4001);
Use IS_PAYLOAD_REQUIRED.intValue()
or IS_PAYLOAD_REQUIRED.stringValue()
. I am not showing the implementation of the class here because it is trivial.
The second is obviously safer but I am wondering if it is an overkill.
int
and converting toString
before comparing is that no one will try to get clever and change it to "4001A". (Which in your example, would generate no exceptions.) Also, it may be that the compiler is smart enough to only do that conversion once.