问题描述
两个方法intValueOf
和intValueOfOptional
,非常相似。
我想修改实现,使这两种方法尽可能少地使用重复代码。
这两种方法都包含非常复杂的条件。我怎样才能简化它们, 将条件的语义相关部分转换为具有有意义名称的变量?
我应该为此使用 IntelliJ 的哪些重构?
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();
}
}
}
}
解决方法
您不需要任何工具,只需查看代码中的区别即可。这是相同的逻辑,尽管当它不是有效的 int
时抛出,另一个返回空的 Optional
。
只需在另一个中利用一个,例如
public static int intValueOf(String str) {
return intValueOfOptional(str).orElseThrow(() -> new NumberFormatException(str));
}