引數校驗

ZeroWM發表於2019-01-15

目的:

  1. 確保引數合法,有效
  2. 節省整個程式時間,提高使用者體驗

 

常見校驗:

1.非空校驗

     常見樣例:   

 private void validate(Request request) {

        ensureParameterExist(request, "引數為空");

 }



public static void ensureParameterExist(Object parameter, String error) {

        if (parameter == null) {

            throw new SdkException(ErrorCodeEnum.BUSINESS_EXCEPTION_INVALID_PARAMETERS, error);

        }

        if (parameter.toString().isEmpty()) {

            throw new SdkException(ErrorCodeEnum.BUSINESS_EXCEPTION_INVALID_PARAMETERS, error);

        }

 }

2.公私鑰驗證

3. 強制引數使用列舉

常見樣例:

public enum  DirectionEnum {

       NORTH("north","北"),

       CENTER("center","中間"),

       SOUTH("south","南");



       private String directionCode;

       private String directionDes;



       DirectionEnum (String directionCode, String directionDes){

           this.directionCode = directionCode;

           this.directionDes = directionDes;

       }

       public String getDirectionDes() {

           return directionDes;

       }



       public void setDirectionDes(String directionDes) {

           this.directionDes = directionDes;

       }



       public String getDirectionCode() {

           return directionCode;

       }



       public void setDirectionCode(String directionCode) {

           this.directionCode = directionCode;

       }

}

 

相關文章