Calling equals on string literal

后端 未结 8 1276
再見小時候
再見小時候 2020-12-29 04:32

I just was tidying my code a bit and there was this piece:

String saving = getValue();
if(saving != null && saving.equals(\"true\")){
   // do someth         


        
8条回答
  •  再見小時候
    2020-12-29 05:08

    if ("true".equals(saving))
    

    is perfectly "save" and recommended by dummy product as SonarLint and any other advisors that establish this "well" thinked rule that your chief request that you follow.

    I say stupid and my explanation is the following.

    What happens if you have following code

    if (!saving.equals("true"))
        {
        if (saving.length() > 10)
            {
            // do something
            }
        }
    

    You can use following advised code

    if (!"true".equals(saving))
        {
        if (saving.length() > 10)
            {
            // do something
            }
        }
    

    But when your code is deployed on production, the program will crash on length() function if saving variable has not been initialized and contains NULL.

    You have changing your code to avoid NullPointerException on equals() function but your program will return another NullPointerException on length() function !

    The good reaction is to stop to use String literal tip and to analyze code to find a perfect solution as in the following example.

    if (saving != null)
        {
        if (!saving.equals("true"))
            {
            if (saving.length() > 10)
                {
                // do something
                }
            }
        }
    

    or

    if (saving == null) saving = "";
    
    if (!saving.equals("true"))
        {
        if (saving.length() > 10)
            {
            // do something
            }
        }
    

    Is is perhaps verbose but if you will use Java for programming it is the price to pay.

    Using String literal equals() method to avoid NullPointerException has the following disadvantages

    1. the solution is tricky
    2. the code is not naturally readable for human
    3. equality will not crash but another part of program will continue to crash
    4. code become quickly difficult to read if this tips is used for lower() and greater() functions (example: if ('USA'.greater(sCode)))
    5. give a false impression that the code is safe

提交回复
热议问题