[Experience] is not empty judgment on Java,

When writing the project encountered a problem

Suppose there is a control layer interface:

    @ResponseBody
    @RequestMapping(value = "test", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public Result<String> test(String user, String number, String time){
        String type="error";
        try{
            rType = SendType.create_send.toString();
            return firstSendService.createSend(type,uName, pNum, time);
        }catch (Exception ex){
            LOGGER.error(ex.getMessage(), ex);
        }
        return Result.failure(type, "fail of connect");
    }

The front when calling this interface, and did not pass parameters, so the user, number, time will default to null.

Then in the service layer, there is a method

    public Result<String> createSend(String type, String user, String number, String time) throws Exception {
        String token = "not fond";
        try{
            if(user.isEmpty() && StringUtils.isBlank(user)){
                return Result.failure(type, "user is not null");
            }
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(user).append(time);
            String signChar = stringBuffer.toString();
            token = TokenUtil.sign(signChar);
        }catch (Exception ex){
            LOGGER.error(ex.getMessage(), ex);
        }
        return Result.success(type, token);
    }

Wherein the verification about the parameters 

if(user.isEmpty() && StringUtils.isBlank(user)){
    return Result.failure(type, "user is not null");
}

Here's judgment conditions are not to be performed, to verify a bit 

  

In other words, a method

     

Then look at StringUtils.isBlank ();

 

Then become null "" Try,

 

No problem, then try again StringUtils.isNotBlank ();

As shown above, isNotBlank () judgment is now turn of isBlank () of.

So, we come to a conclusion:

(0) for isEmpty (), when the character string is "" When, return true; however isEmpty () can not be used is determined null string, the null pointer exception will report errors,

Therefore isEmpty () to write more appropriate if (str == "" && str.isEmpty ()) {return}

 

(1) 相较于 isEmpty()  只能判断 "" 的字符串, isBlank() 的功能性要更大更完善一些, 当字符串为 null 时, isBlank()  为 true; isNotBlank() 则跟 isBlank() 相反, 为 false.

所以 isBlank()  更适合写 if( str == null && StringUtils.isBlank(str)){ return }  或者  if( str == "" && StringUtils.isBlank(str)){ return } 

 

但是

这样是不行的, 看来 isBlank() 好像看起来要更加全能一些, 因为有时候参数有可能为 null, 也有可能为"" ,用 isBlank() 的话可以避免服务器停掉, 如何优雅的抛出错误或者异常, 且避免服务器的运行因此受到影响, 是我在努力的一个方向, 希望这些可以有些帮助

 

再补上一点 

 

这就奇怪了, 话说上面的 if( a.isEmpty() || StringUtils.isBlank(a)){ } 中, || 不是如果左边不成功就使用右边的判断条件么? 为什么会直接报错呢? 那如果是 || 的判断是先判断左边, 那在 a == "" 的时候,为什么又可以成功运行? isEmpty() 这么坑的么?

 

再来一组对比

 

  

那还是强烈推荐使用  isBlank()  吧, "" 和 isEmpty() 是局限性有点大, 灵活性不够高, 容易出事....

 

 

 

 

 

  

 

Guess you like

Origin www.cnblogs.com/unityworld/p/11419864.html