为什么不建议你用去 “! = null” 做判空?
阅读本文大概需要 3.5 分钟。
来自:stackoverflow
...if (someobject != null) {
someobject.doCalc();}...
public interface Action {
void doSomething();}
public interface Parser {
Action findAction(String userInput);}
public class MyParser implements Parser {
private static Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};
public Action findAction(String userInput) {
// ...
if ( /* we can't find any actions */ ) {
return DO_NOTHING;
}
}}
Parser parser = ParserFactory.getParser();
if (parser == null) {
// now what?
// this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
// do nothing} else {
action.doSomething();}
ParserFactory.getParser().findAction(someInput).doSomething();
"bar".equals(foo)
foo.equals("bar")
推荐阅读:
内容包含Java基础、JavaWeb、MySQL性能优化、JVM、锁、百万并发、消息队列、高性能缓存、反射、Spring全家桶原理、微服务、Zookeeper、数据结构、限流熔断降级......等技术栈!
⬇戳阅读原文领取! 朕已阅
评论