如何验证set方法中的值?

时间:2014-12-30 14:22:21

标签: java oop

我最近开始学习面向对象编程,我有一个问题。 例如,我正在做一个名为student的课程,我有他的ID,所以我打算写一个setID方法

  public int setID(idval)
   {if(idval>=0 &&idval<=100) 
        ID=idval;
    else system.out.print("Invalid ID");
   }

我的问题是,我是否需要让用户输入另一个ID,因为第一个无效。 如果第一个ID无效,用户可以再次尝试另一个ID吗?

5 个答案:

答案 0 :(得分:1)

优良作法是让用户以某种方式知道他们传递了错误的价值。

对此没有一刀切的方法,但抛出Exception并记录您的期望(using JavaDoc)是两种不错的方法。

此外,设置者返回值并不是惯用的Java。

如果我要重写(并重新格式化)你的代码,我会这样做:

/**
 * Set the ID 
 * @param idval An integer between 0 and 100, inclusive.
 * @throws IllegalArgumentException if ID is out of range.
 **/
public void setID(int idval) {
    if(idval >= 0 && idval <= 100) {
       ID = idval;
    } else {
       throw new IllegalArgumentException("Value must be between 0 and 100");
    }
}

答案 1 :(得分:0)

我认为Bean Validation可以成为验证POJO(bean)的一个很好的起点。它将bean验证代码从POJO移到外部验证器。

如果您在Java EE容器内工作,或者您正在使用例如Spring你可以非常简单地启用bean验证并使用可用的注释。

请注意,此验证通常放在字段或getter上 - 而不是setter

一些注释是:

  • @NotNull
  • @Null
  • @Max
  • @Min
  • @AssertFalse
  • @Size

示例可以是@NotNull注释,可以像这样使用:

@NotNull
private String name;

验证对象时,验证程序检查该属性是否为空。很简单;)

如果您想以编程方式对setter进行验证,我建议您记录JavaDoc中所期望的内容或所有开发人员共享的单元测试(后一种选择只是 internal <的选项/ em>项目)。

然后我建议您使用某种断言实用程序来避免代码混乱。例如。 Spring Framework使用Assert类。

/**
 * Sets foo, does not accept null values.
 * @param foo Must not be null.
 */
public void setFoo(String foo) {
    Assert.notNull(foo, "Foo must not be null");
    this.foo = foo;
}

有关验证主题的一些资源:

答案 2 :(得分:0)

这是一个简单易用的例子,希望它可能会有所帮助。

public class Student {
private long Id;

public long getId() {
    return Id;
}

public void setId(long id) {
    if (id >= 0 && id <= 100) {
        this.Id = id;
    } else {
        throw new IllegalArgumentException();
    }
}

public static void main(String[] args) {
    Student student = new Student();
    Console console = System.console();
    String input = null;
    System.out.println("Input a valid student id");
    while ((input = console.readLine()) != null) {
        try {
            input = input.replaceAll("^\\s+", "").replaceAll("\\s+$", "");
            if (input.length() > 0) {
                student.setId(Long.valueOf(input));
                break;
            } else {
                System.out.println("Input a valid student id");
                continue;
            }
        } catch (IllegalArgumentException e) {
            System.out.println("Input a valid student id");
            continue;
        }
    }
    System.out.println("Student id is " + student.getId());
}
}

答案 3 :(得分:0)

您可以执行以下操作。这将代码分成单独的方法。这是您应该如何创建方法。他们应该做具体的事情。这也使用递归,这是一个方法调用自身直到满足条件。

private int idval = 0;

public int getIdval() {
    return idval;
}

public void setIdval(int idval) {
    this.idval = idval;
}

private boolean isValidId(int idValue){
    if(idValue >= 0 && idValue <= 100){
        return true;
    }
    else{
        return false;
    }
}

public void userId(){

    Scanner reader = new Scanner(System.in);
    System.out.print("Enter ID: ");
    int id = reader.nextInt();

    if(isValidId(id)){
        setIdval(id);
    }
    else{
        System.out.println("Invalid ID")
        userId();
    }

    reader.close();
}

答案 4 :(得分:-2)

正确的方法是运用责任分离原则。将验证留在其他地方,如服务层或GUI层。