简体   繁体   English

在哪里验证String参数

[英]Where to validate String parameter

I have a Student class that has to have a property of a String ID, which has to be validated. 我有一个Student类,该类必须具有字符串ID的属性,该属性必须经过验证。 I'm not sure whether to validate it inside the student class or the class that I'm implementing the Student class in. Does that make sense? 我不确定是否要在学生班级或要在其中实施学生班级的班级中对其进行验证。这有意义吗?

Assuming ID is final and immutable, then one approach is to have Student constructor throw an exception, probably new IllegalArgumentException("Invalid student ID"); 假设ID是最终的且不可变,则一种方法是让Student构造函数引发异常,可能是new IllegalArgumentException("Invalid student ID");

You may additionally provide static method in Student class, which verifies if string is valid, in case you need to check it without creating Student object. 您还可以在Student类中提供静态方法,以验证字符串是否有效,以防您需要在不创建Student对象的情况下进行检查。

But the logic of determining if ID is valid or not should be in the Student class, I think. 我认为,确定ID是否有效的逻辑应该在Student类中。

If there are (or can be in future) different kind of student IDs, you could also consider abstract factory pattern, but sounds like that is bit of an overkill. 如果有(或将来可能会有)不同种类的学生证,您也可以考虑使用抽象工厂模式,但这听起来有些过头。

If Student already has any business inside use validate inside else use second one 如果学生已经在内部使用任何业务,请在内部进行验证,否则使用第二个

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

Inside of Model or controller or Action 在模型或控制器或动作内部

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

One of the approach is to use validation object. 方法之一是使用验证对象。 For instance see the Validation approach uses in the Spring Framework. 例如,请参见Spring框架中使用的Validation方法。 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. 您创建一个对象,该对象使用两种方法来实现接口Validator :一种用于检测Validator是否可以验证要验证的实例,另一种用于验证实例。

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). 即使不遵守类层次结构(POJO原则),您也可以组合多个Validator。
  • 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. 当您需要使用来自其他系统(例如数据库)的数据来验证字段时,此方法避免在POJO域类中混合数据库/持久性代码。

Please see the documentation of Spring about Validation . 请参阅有关验证的Spring文档

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

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