Java :如何处理空指针?

2019-12-31 11:16:04 +08:00
 sandman511
Integer code = getCode();
String codeMeaning = code == null ? null :
                    code == 1 ? "你好" :
                    code == 2 ? "你好好" :
                    code == 3 ? "你好好好";

请各大佬帮忙修改这段代码
code == null ? null 看起来有点怪怪的

5647 次点击
所在节点    程序员
57 条回复
avk458
2019-12-31 11:25:38 +08:00
三元表达式还能这样玩儿?
按照这个`codeMeaning`的意思来用 switch 是不是更好?
包装类比较是不是应该用 equals ?
pmispig
2019-12-31 11:27:02 +08:00
谁写的,先把他头锤爆
Lin0936
2019-12-31 11:28:53 +08:00
// TODO: Bullshit
sandman511
2019-12-31 11:34:59 +08:00
@pmispig 实不相瞒。。我写的。。
manami
2019-12-31 11:36:53 +08:00
Objects.equals(a, b)
optional
2019-12-31 11:37:00 +08:00
// 第一种提前返回
```
if (Objects.isNull(code)) {
return null;
}
//switch or if
```
//第二种,
```
Optional.ofNullable(code).map(code->{
//switch or if
}).orElse(null);
```
passerbytiny
2019-12-31 11:37:08 +08:00
一,Java 没有指针;
二,三元连接符嵌套使用是大忌;
三,if(some == null) { //bulabula when null }else{ //bulabula when not null},或者 if(some != null){bulabula},或者 some.ifPresent((value)->{/bulabula}), 是良好的编码习惯;
四,请善用默认值:
Integer code = getCode();
String codeMeaning == null ;// 或者 "默认值"
if(code != null){
switch (code.intValue()){
case 1 : codeMeaning = "你好"; break;
// ......
}
}
sandman511
2019-12-31 11:38:17 +08:00
@avk458 我嫌 switch 写起来太麻烦了 这个逻辑比较简单 就三行 所以用了三元。。。请教一下三元不能这样用吗?
确实该用 equals,但是 code 可能为 null,equals 可能抛空指针。。所以不知道该咋办了
lff0305
2019-12-31 11:40:35 +08:00
```
Optional<Integer> code = Optional.ofNullable(getCode());
String s = code.map(c -> {
switch (c) {
case 1: return "one";
case 2: return "two";
}
return "other";
}).orElse(null);
```
ily433664
2019-12-31 11:44:24 +08:00
Map<Integer, String> map = new ....
codeMeaning = map.get(code);
littleylv
2019-12-31 11:44:46 +08:00
实不相瞒,三元这么嵌套不加括号的,除了傻逼笔试题外,工作中这样写的同事我会打死他(不是不能嵌套,你得加括号增加可读性)
lihongjie0209
2019-12-31 11:54:00 +08:00
不加括号就是作死
w292614191
2019-12-31 11:55:22 +08:00
我感觉比楼上那些 if else switch 好看多了。

都是些秀无意义代码的。

你看看 7、9 楼,

硬是加长代码,毫无意义。
Jimmy2Angel
2019-12-31 11:58:35 +08:00
@passerbytiny 一,你真是个合格的杠精
ipwx
2019-12-31 12:01:09 +08:00
private static final String[] lookup = {null, "你好", "你好好", "你好好好"};
String codeMeaning = lookup[code != null? code.intValue() : 0];

https://ideone.com/7rXSyK
matepi
2019-12-31 12:11:15 +08:00
enum 特性都多少年了吧
banmuyutian
2019-12-31 12:11:53 +08:00
@w292614191
“硬是加长代码,毫无意义。”?
等你看到那些难以阅读维护的代码就知道代码规范的重要性了
micean
2019-12-31 12:12:24 +08:00
挺清晰的,加啥括号?有换行和缩进还不够吗?
lhx2008
2019-12-31 12:14:49 +08:00
enum 吧,或者 map
code 的话,null 就整个-1 呗,null 来 null 去的
wysnylc
2019-12-31 12:18:23 +08:00
optional+switch,或者用 java 13 还是 14 的新 switch

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/633824

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX