Two methods intValueOf
and intValueOfOptional
, which are very similar.
I would like to modify the implementation so that the two methods use as little duplicated code.
Both methods contain a very complex condition. How can I simplify them, semantically related parts of the condition into variables with meaningful names?
Which refactorings from IntelliJ should I use for this?
public static int intValueOf(String str) {
int idx = 0;
int end;
boolean sign = false;
char ch;
if ((str == null) || ((end = str.length()) == 0) || ((((ch = str.charAt(0)) < '0') || (ch > '9')) && (!(sign = ch == '-') || (++idx == end) || ((ch = str.charAt(idx)) < '0') || (ch > '9')))) {
throw new NumberFormatException(str);
}
int ival = 0;
for (; ; ival *= 10) {
ival += '0' - ch;
if (++idx == end) {
return sign ? ival : -ival ;
}
if (((ch = str.charAt(idx)) < '0') || (ch > '9')) {
throw new NumberFormatException(str);
}
}
}
public static Optional<Integer> intValueOfOptional(String str) {
int idx = 0;
int end;
boolean sign = false;
char ch;
if ((str == null) || ((end = str.length()) == 0) || ((((ch = str.charAt(0)) < '0') || (ch > '9')) && (!(sign = ch == '-') || (++idx == end) || ((ch = str.charAt(idx)) < '0') || (ch > '9')))) {
return Optional.empty();
}
int ival = 0;
for (; ; ival *= 10) {
ival += '0' - ch;
if (++idx == end) {
return Optional.of(sign ? ival : -ival);
}
if (((ch = str.charAt(idx)) < '0') || (ch > '9')) {
return Optional.empty();
}
}
}
}
You don't need any tools for that, just look at the distinctions in the code. It's the same logic although one throws when it's not a valid int
where the other returns an empty Optional
.
Just leverage one within the other e.g.
public static int intValueOf(String str) {
return intValueOfOptional(str).orElseThrow(() -> new NumberFormatException(str));
}