Java :如何处理空指针?
Integer code = getCode(); String codeMeaning = code == null ? null : code == 1 ? "你好" : code == 2 ? "你好好" : code == 3 ? "你好好好";
请各大佬帮忙修改这段代码
code == null ? null 看起来有点怪怪的
Integer code = getCode(); String codeMeaning = code == null ? null : code == 1 ? "你好" : code == 2 ? "你好好" : code == 3 ? "你好好好";
请各大佬帮忙修改这段代码
code == null ? null 看起来有点怪怪的
都是些秀无意义代码的。
你看看 7、9 ,
硬是加长代码,毫无意义。
https://ideone.com/7rXSyK
table.get(xx)
你的 getUnit(type) 应该直接返回这个 unit class。
@Override
public boolean unknown() {
return true;
}
};
/**
* e.g. kg, g, t
*/
@Getter
private String note;
static UnitOfWeight[] units = UnitOfWeight.values();
/**
* kg’s enums
*/
static int[] kgs = {1, -1, 4};
/**
* gram’s enums
*/
static int[] grams = {2, 0, 5};
/**
* ton’s enums
*/
static int[] tons = {3, 1, 6};
UnitOfWeight(String note) {
this.note = note;
}
public static UnitOfWeight valueOf(Integer unit) {
for (UnitOfWeight ofWeight : units) {
if (unit == null) {
return UNKNOWN;
}
if (ofWeight.match(unit)) {
return ofWeight;
}
}
return UNKNOWN;
}
/**
* 获取对应枚举
* @param unit
* @return
*/
public abstract boolean match(int unit);
/**
* 错误的值
* @return
*/
public boolean unknown() {
return false;
}
public static void main(String[] args) {
Integer unit = null;
//getUnit (type2);
UnitOfWeight ofWeight = UnitOfWeight.valueOf(unit);
if (!ofWeight.unknown()) {
String transferredUnit = ofWeight.getNote();
//…
}
}
}
根据你 append 的代码用了一个枚举来做, 根据你的描述我想有几个点需要扩展,
1. 从 pdf 解析 type 值;
2. 有很多情况(可能因为历史原因很多地方使用了不同的值代表某一个单位);
所以我建议使用枚举, 原因是:
1. 我觉得后面随着业务需要或者其他原因重构, 可能慢慢的这些代表某一个单位的值会改变或者统一为一个,所以你需要修改 通过枚举可以统一在一处,便于修改;
2. 再者也方便返回的字符值变更 总之对于变更这个枚举类基本上可以应对 90%以上的情况;
3. match 方法可以做针对行的扩展和优化;
// Using this map
String codeMeaning = codeMeaningInfo.get(code);
“`
一般情况下 Map 应该全局唯一,另外推荐 Kotlin 的 `when` 表达式。
回头看一下,还是 null 太多了,null 这东西还是不要在正常流程中出现吧
code == null ? null :
code == 1 ? “你好” :
code == 2 ? “你好好” :
code == 3 ? “你好好好” :
“其他”;
这不就是一个简易秒懂的 switch,上其他代码也做不到这么工整
final String name =
code == null ? “” :
code == 1 ? “你好” :
code == 2 ? “你好好” :
code == 3 ? “你好好好” :
“其他”;