Optimistic way of checking null references in java

This question already has an answer here:

  • Avoiding != null statements 58 answers

  • add("x_Amount", amount);
    add("x_Currency_Code", currency);
    add("x_Exp_Date", expDate);
    
    void add(String name, String value)
    {
        if(value!=null && !value.isEmpty())
            AIMRequest.put(name, value); 
    }
    

    According your if 's, conditions you are comparing String s, so make a method:

    public boolean isValid(String s) {
        return s != null && s != "" && !s.isEmpty();
    }
    

    If you want to compare objects with this methods change the signature public boolean isValid(Object o) ,

    and your code will be clean as this:

    if(isValid(amount))
            AIMRequest.put("x_Amount", amount);
    
    if(isValid(currency)
            AIMRequest.put("x_Currency_Code", currency);
    
    if(isValid(expDate)
            AIMRequest.put("x_Exp_Date", expDate);
    

    But if you can collect all objects in an array :

    public boolean isValid(Object[] os) {
        for (String s : os) {
            boolean isValid = s != null && s != "" && !s.isEmpty();
            if (!isValid) return false;
        }
        return true;
    }
    

    This method will accept an array of objects and loop through them to check for any undefined object or null or empty.

    public Object[] checkForNull(Object[] objects){
        for(int i = 0;i<objects.length;i++){
        //check all conditions for null empty or no data.
            if(objects[i]!= null && objects!= "" && !objects[i].isEmpty()) 
                 object[i] = "UNDEFINED";
        return objects[];
    }
    

    So now you can pass all the objects u want to check for empty or undefined or null and then in your case where u want to use all u need to do is check: if(object == "UNDEFINED")

    Hope it helps.

    链接地址: http://www.djcxy.com/p/13304.html

    上一篇: 如何在Java中优雅地处理空值

    下一篇: 在java中检查空引用的乐观方式