Home  >  Q&A  >  body text

关于java方法里的非空判断的疑问,谢谢

    public static void main(String[] args) {
        String result = replaceStr("jaja");
        if (result != null) {            //在这里又要判断下非空
              int count = 50 + Integer.parseInt(result);
        }
    }
    
    public static String replaceStr(String tem){
        String result;
        if (tem == null) {
            result = null;
        } else {
            String substring = tem.substring(0, 1);
            result = substring;
        }
        return result;
    }

如上代码,我的疑惑时,当参数tem为空,方法返回null,那岂不是又要在调用replaceStr这个方法的地方又要判断次返回值是否为null?那这个代码看上去不是很难看,好多if(**!=null)这样的语句。

我想问的是:有没有一种设计,可以只要在一处判断非空,其他地方只要写业务逻辑就行了?

谢谢

天蓬老师天蓬老师2718 days ago290

reply all(8)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 17:59:57

    And your question is a bit confusing and I can’t understand what question you want to ask.

    reply
    0
  • 黄舟

    黄舟2017-04-17 17:59:57

    First of all, your code is wrong

            if (tem != null) {
                result = null;
            } else {
                String substring = tem.substring(0, 1);
                result = substring;
            }  

    It should be if (tem == null)
    其次,即使这样改过来还是不够严谨,tem=""elseThere is something wrong inside.
    Again, just judging it as null twice is too much.
    Finally, the number of judgments is based on your business logic. Even if the number of judgments is reduced in one place, it still has to be repaid in other places.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 17:59:57

    If you don’t use null as the return value of the method, you don’t need to detect null. For example, in your example, just return "0".

    reply
    0
  • PHPz

    PHPz2017-04-17 17:59:57

    If you are sure your term入参在正常业务场景下必须不能为null,那么没必要去做null值得判断,尽早抛出空指针异常 is reasonable.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 17:59:57

    You can reduce non-empty judgments through strict design of business logic, but you still cannot guarantee the distortion caused by maintaining the code. Therefore, for the sake of the robustness of the code, it is better to judge first before use. If the scattered code str == null || "".equals(str) is not good-looking, you can use your own packaging tool Or use open source tools, such as apache's StringUtils, etc.

    reply
    0
  • PHPz

    PHPz2017-04-17 17:59:57

    Changed your code:

        public static String replaceStr(String tem){
            if (tem == null || tem.length() == 0) {
                return null;
            }
            return tem.substring(0, 1);
        }

    First of all, it is unavoidable to determine the business requirement of non-null, or you can add a default value when designing, and use the default value when the return value is null (the specific situation depends on the current situation when the null value is encountered in the business) How to handle one step, or use the default value, or throw an exception, or terminate execution, etc.).

    For the use of default values, you can take a look at guava's MoreObjects#firstNonNull.

    Optional in java8 is to solve this problem of null judgment (in fact, judgment is still unavoidable, but it is just a different way to avoid NullPointerException), you can also take a look.

    In addition, directly ctrl+c spring's StringUtils#replace method is given to you (for the same reason, you can also refer to apache common's StringUtils. Anyway, there is no shortage of StringUtils in the Java world). You can refer to how others implement it.

    /**
         * Replace all occurrences of a substring within a string with
         * another string.
         * @param inString {@code String} to examine
         * @param oldPattern {@code String} to replace
         * @param newPattern {@code String} to insert
         * @return a {@code String} with the replacements
         */
        public static String replace(String inString, String oldPattern, String newPattern) {
            if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {
                return inString;
            }
            StringBuilder sb = new StringBuilder();
            int pos = 0; // our position in the old string
            int index = inString.indexOf(oldPattern);
            // the index of an occurrence we've found, or -1
            int patLen = oldPattern.length();
            while (index >= 0) {
                sb.append(inString.substring(pos, index));
                sb.append(newPattern);
                pos = index + patLen;
                index = inString.indexOf(oldPattern, pos);
            }
            sb.append(inString.substring(pos));
            // remember to append any characters to the right of a match
            return sb.toString();
        }

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 17:59:57

    Personal approach:

    1. Unless you need to return null, don’t return a null value; don’t pass a null value ["Clean Code" also says this]

    2. If null is not returned, the first way is to throw NPE directly; the second way is to use Optional (this can prevent us from forgetting the !=null check, and at the same time it looks more elegant than everywhere!=)

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 17:59:57

    This code makes no sense

    reply
    0
  • Cancelreply