Elegant writing method in java 01-Business judgment and assertion-Assert tool class

Understanding of assertions: Assert that it satisfies the condition and does not throw an exception; generates an exception when the assertion is not satisfied;

Business requirement: Determine whether a query object is empty and directly return error information

Common writing methods:

if (ObjectUtil.isNull(object)){
    
    
return XXXX
}

How to write Assert
The meaning of this code is to prompt and return an exception message if the object is empty. The exception message is captured and returned by unified exception

 Assert.isFalse(ObjectUtil.isNull(object), StatusEnum._NOT_EXIST, param);

I used the hutool toolkit.

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.18</version>
        </dependency>

Look at the source code

    public static void isFalse(boolean expression, String errorMsgTemplate, Object... params) throws IllegalArgumentException {
    
    
        isFalse(expression, () -> {
    
    
            return new IllegalArgumentException(StrUtil.format(errorMsgTemplate, params));
        });
    }

expression: the condition you need to judge

errorMsgTemplate: Exception message template prompted

params: Parameters to be replaced in the exception message

Example:

   Assert.isFalse(1 == 1,"提示消息{}","我是消息值");

Insert image description here
test code

import cn.hutool.core.lang.Assert;

public class StringTest {
    
    

  public static void main(String[] args) {
    
    

    Assert.isFalse(1 == 1,"提示消息{}","我是消息值");


  }
}

Message templates are written together using an enumeration class

Guess you like

Origin blog.csdn.net/hai411741962/article/details/134853415