判空前后顺序的思考(代码规范)


判空前后顺序的思考

判空应该在前还是在后?


提示:以下是本篇文章正文内容,下面案例可供参考

一、判空前后什么意思?

直接上代码,一个较小的细节。

    @Test
    public void testStringNull(){


        String x = null;
        if (x == null){
            System.out.println("xxxx");
        }


        if (null == x){
            System.out.println("yyyy");
        }


        if ("".equals(x)){
            System.out.println("NNNN");
        }


        if (x.equals("")){
            System.out.println("MMMM");
        }


 

结果展示:

xxxx
yyyy


java.lang.NullPointerException
	at test20200909.Test0909.testStringNull(Test0909.java:76)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)

二、结论

结论:针对if(str == null)和if(null == str)其实本质上是没有区别的,大部分人的习惯也是前者,但是后者符合极限编程写法。所以这个取决于个人习惯问题。

但是对于equals方法,就不尽相同了。在if(str.equals(""))中如果x为null,则会报出空指针错误,而if(“”.equals(str))会避免空指针错误!

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页