1

我有一个必须具有字符串 ID 属性的学生类,该属性必须经过验证。我不确定是在学生班级还是在我正在实施学生班级的班级中验证它。这有意义吗?

4

3 回答 3

5

假设 ID 是最终的且不可变的,那么一种方法是让 Student 构造函数抛出异常,可能new IllegalArgumentException("Invalid student ID");

您可以在 Student 类中另外提供静态方法,该方法验证字符串是否有效,以防您需要在不创建 Student 对象的情况下检查它。

但我认为,确定 ID 是否有效的逻辑应该在 Student 类中。

如果有(或将来可能有)不同类型的学生 ID,您也可以考虑抽象工厂模式,但这听起来有点矫枉过正。

于 2012-10-28T17:46:29.267 回答
1

如果学生内部已经有任何业务,请在内部使用验证,否则使用第二个

Class Student
{
 public boolean  validate ()
  {
   //some logic to validation
  }
}

模型或控制器或动作内部

 public boolean  validate ()
  {
   //some logic to validation
  }
于 2012-10-28T17:47:56.657 回答
1

One of the approach is to use validation object. For instance see the Validation approach uses in the Spring Framework. You create an object which implements the interface Validator with two methods: one to detect if the Validator can validate the instance to validate, and another one which validate it.

public class StudentValidator implements Validator<Student> {

  public boolean supports(Student student) {
   // ...
  }

  public void validate(Object target, Errors errors) {
   // ...
  }
}

This approach leads to separation of the code of the object and the way to validate it, offering more flexibility when combining validator:

  • you can combine several Validator even if the class hierarchy is not respected (POJO principle).
  • when you need to validate field with data from other system (for instance a database), this approach avoid to mix database / persistence code in the POJO domain class.

Please see the documentation of Spring about Validation.

于 2012-10-28T17:55:02.357 回答