Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit ee5bfae

Browse filesBrowse files
committed
no message
1 parent 6173090 commit ee5bfae
Copy full SHA for ee5bfae

File tree

Expand file treeCollapse file tree

1 file changed

+6
-5
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+6
-5
lines changed

‎contents/avoiding-null-statements-in-java.md

Copy file name to clipboardExpand all lines: contents/avoiding-null-statements-in-java.md
+6-5Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@ public interface Parser {
5050

5151
我们来改造一下
5252

53-
类定义如下,这样定义findAction方法后,确保无论用户输入什么,都不会返回null对象
53+
类定义如下,这样定义findAction方法后,确保无论用户输入什么,都不会返回null对象:
54+
```java
5455
public class MyParser implements Parser {
5556
private static Action DO_NOTHING = new Action() {
5657
public void doSomething() { /* do nothing */ }
@@ -62,7 +63,7 @@ public class MyParser implements Parser {
6263
return DO_NOTHING;
6364
}
6465
}}
65-
66+
```
6667

6768
对比下面两份调用实例
6869
1. 冗余: 每获取一个对象,就判一次空
@@ -90,11 +91,11 @@ ParserFactory.getParser().findAction(someInput).doSomething();
9091
- 如果要用equal方法,请用object<不可能为空>.equal(object<可能为空>))
9192
例如:
9293
使用
93-
"bar".equals(foo)
94+
`"bar".equals(foo) `
9495
而不是
95-
foo.equals("bar")
96+
`foo.equals("bar") `
9697
- Java8或者guava lib中,提供了Optional类,这是一个元素容器,通过它来封装对象,可以减少判空。不过代码量还是不少。不爽。
9798
- 如果你想返回null,请挺下来想一想,这个地方是否更应该抛出一个异常
9899

99100
stackoverflow链接:
100-
http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java?page=2&tab=votes#tab-top
101+
http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java?page=2&tab=votes#tab-top

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.