繁体   English   中英

如何在Java中验证可选参数

[英]How to validate optional parameters in Java

我有一个方法可以接受10个参数,其中8个是强制性的。 为了检查8/10是否不具有空值,我为每个参数设置了一堆if-else语句。

编写此if-else代码对我来说似乎很微不足道。 有更好的方法吗?

谢谢卑诗省

您可以使用类来封装参数。 这样,在您的类中,您可以使用一种方法来检查它们的有效性。

就像是:

class MethodParams {
    private String p01;
    private String p02;
    private String p03;
    private String p04;
    private String p05;
    private String p06;
    private String p07;
    private String p08;
    private String p09;
    private String p10;

    // getter & setters

    public boolean validate() {
        // validate parameters here
    }


}

class A {
    public methodWith10(MethodParams mp) {
        if (!mp.validate()) {
            // do something and fail
        }
        // methodWith10 implementation follows...
    }
}

您可以使用apache commons-lang库来验证您的输入参数:

Validate.notNull(param, "This param can not be null"); // the message is optional

Guava的Preconditions.checkNotNull方法对此很有用。

我承认以下内容是高级的,它需要使用3rd party jars,但请看一下OVal:

4.2.2。 声明方法参数的约束

例如:

@Guarded 
public class BusinessObject
{
  public void setName(@NotNull String name)
  {
    this.name = name;
  }
  ...
}

如果嵌套的if..else语句困扰您,则可以一次检查一个参数,并在第一个失败后立即返回。

因此,如下所示:

if (firstParm == null) {
  err = "firstParam is required.";
  return false;
}

if (secondParam == null {
  err = "secondParam is required.";
  return false;
}

// If we made it this far, we have all the required parameter values

您当然会注意到此方法的缺点,即调用者在传入有效的第一个参数之前不会知道第二个参数是必需的。 但是,这种类型的实现很常见。

为了改善这一点,您可以像下面这样:

err = "";
boolean ok = true;

if (firstParm == null) {
  err = "firstParam is required.";
  ok = false;
}

if (secondParam == null {
  err = err + " secondParam is required.";
  ok = false;
}

if (! ok) {
  return false;
}

// If we made it this far, we have all the required parameter values

这对您有用吗? 而不是“为每个参数使用一堆if-else语句”,每个参数都有一个三元操作:

  public static void foo(String a, String b, String c, String d, String e, String f, String g, String h, String i, String j) {
    int validCount = 0;
    validCount += (a != null) ? 1 : 0;
    validCount += (b != null) ? 1 : 0;
    validCount += (c != null) ? 1 : 0;
    validCount += (d != null) ? 1 : 0;
    validCount += (e != null) ? 1 : 0;
    validCount += (f != null) ? 1 : 0;
    validCount += (g != null) ? 1 : 0;
    validCount += (h != null) ? 1 : 0;
    validCount += (i != null) ? 1 : 0;
    validCount += (j != null) ? 1 : 0;

    if(validCount < 8)
      System.out.println("Invalid");
    else
      System.out.println("Valid");
  } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM