一个简单的优雅的简洁的字段校验工具


前言

做了好几个项目,发现这些项目的字段检查要么是通过写很多if来判断;要么是为每个入参定义一个实体,然后使用某些框架,通过再实体的属性加注解来判断;个人觉得第一种方式代码很冗余且不简洁不够优雅;第二种方式导致实体类很多;因此总结了一下,实现通过一行代码来做字段检查


一、效果

传统的方式,字段多的话很冗余

/**
     * 传统方式:很多if不够优雅
     * @return
     */
    public static OptResult fieldCheckOld(){
        try{
            String username = "zhangsan";
            if (StrUtil.isEmpty(username)){
                throw new BussinessException("username不能为空");
            }

            String password = "";
            if (StrUtil.isEmpty(password)){
                throw new BussinessException("password不能为空");
            }

            String sex = null;
            if (StrUtil.isEmpty(sex)){
                throw new BussinessException("sex不能为空");
            }

            return OptResult.createOk();
        }catch (BussinessException e){
            return OptResult.createFial(e.getMessage());
        }

    }

现在的方式,一行代码搞定

  public static OptResult fieldCheck(){
        try{
            String username = "zhangsan";
            //TODO:重点
            AssertField.isEmpty("username",username);

            return OptResult.createOk();
        }catch (BussinessException e){
            return OptResult.createFial(e.getMessage());
        }
    }

二、实现

1.设计思想

其实是将这些if封装到一个方法中,虽然很简单,但仍有很多的项目还是使用传统的校验方式,很古板

2.项目结构

在这里插入图片描述

3.pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xql</groupId>
    <artifactId>field-check</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <description>字段检查工具</description>

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

</project>

4.其他代码

package com.xql.checker;

import cn.hutool.core.util.StrUtil;
import com.xql.exception.BussinessException;

/**
 * 字段检查器
 */
public class AssertField {


    /**
     * 字符串是不是为空
     * @param fieldName 字段名
     * @param fieldValue 字段值
     */
    public static void isEmpty(String fieldName,String fieldValue){
        if (StrUtil.isEmpty(fieldValue)){
            throw new BussinessException("必輸字段"+fieldName+"不能为空");
        }
    }


    /**
     * 字符串是不是为空
     * @param fieldValue 字段值
     */
    public static void isEmpty(String fieldValue){
        if (StrUtil.isEmpty(fieldValue)){
            throw new BussinessException("必输字段不能为空");
        }
    }
}

package com.xql.exception;

/**
 * 自定义业务异常
 */
public class BussinessException extends RuntimeException {

    /**
     * Constructs a new runtime exception with the specified detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     *
     * @param message the detail message. The detail message is saved for
     *                later retrieval by the {@link #getMessage()} method.
     */
    public BussinessException(String message) {
        super(message);
    }
}

package com.xql.result;

public class OptResult<T> {

    private static String succMsg = "操作成功";
    private static String failMsg = "操作失败";


    private boolean isSuccess = false;

    private String message;

    private T data;

    public static OptResult createOk(){
        OptResult optResult = new OptResult();
        optResult.setSuccess(true);
        optResult.setMessage(succMsg);
        return optResult;
    }

    public static OptResult createFial(){
        OptResult optResult = new OptResult();
        optResult.setSuccess(false);
        optResult.setMessage(failMsg);
        return optResult;
    }

    public static OptResult createFial(String errMsg){
        OptResult optResult = new OptResult();
        optResult.setSuccess(false);
        optResult.setMessage(errMsg);
        return optResult;
    }

    public boolean isSuccess() {
        return isSuccess;
    }

    public void setSuccess(boolean success) {
        isSuccess = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "OptResult{" +
                "isSuccess=" + isSuccess +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}

package com.xql;

import cn.hutool.core.util.StrUtil;
import com.xql.checker.AssertField;
import com.xql.exception.BussinessException;
import com.xql.result.OptResult;

public class Test {
    public static void main(String[] args) {
        OptResult optResult = fieldCheck();
        System.out.println(optResult.toString());
    }


    /**
     * 测试
     * @return
     */
    public static OptResult fieldCheck(){
        try{
            String username = "zhangsan";
            //TODO:重点
            AssertField.isEmpty("username",username);

            return OptResult.createOk();
        }catch (BussinessException e){
            return OptResult.createFial(e.getMessage());
        }
    }


    /**
     * 传统方式:很多if不够优雅
     * @return
     */
    public static OptResult fieldCheckOld(){
        try{
            String username = "zhangsan";
            if (StrUtil.isEmpty(username)){
                throw new BussinessException("username不能为空");
            }

            String password = "";
            if (StrUtil.isEmpty(password)){
                throw new BussinessException("password不能为空");
            }

            String sex = null;
            if (StrUtil.isEmpty(sex)){
                throw new BussinessException("sex不能为空");
            }

            return OptResult.createOk();
        }catch (BussinessException e){
            return OptResult.createFial(e.getMessage());
        }

    }
}

总结

此工具类虽然没有任何难度,但是却是一种思想的转变,这种思想的转变使我们的代码更加简洁优雅,可读性更高

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值