我应该在构造函数中验证参数吗? [英] Should i validate parameters in constructor?

查看:130
本文介绍了我应该在构造函数中验证参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个跟随MVC模式的Web应用程序。



在有效的Java中,作者提到在创建新对象时验证类的构造函数中的参数。



但是我没有创建一些将由第三方使用的API。我的类只接受在beeing被提交到服务器之前验证的表单的输入字段的参数。



所以在这种情况下,我应该用作者提到的方式创建我的类在有效的java或它是无用的?

解决方案

它不像阅读一本书一样明确,实现它所说的。您需要考虑并将知识应用于您的具体情况。



这真的取决于您如何初始化类中的变量,并在对象构建之后立即使用它们: / p>

一些指针:




  • 如果要使用变量通过类中的一些方法或对象将在构造之后重新使用(在大多数情况下会这样),您应该验证所需的值不为空或为空,以避免发生讨厌的异常。 p>


  • 验证输入参数的第二次是当您希望将正确的值设置为特定的内部变量时。如果您需要将参数限制在特定的值范围内,那么验证是非常重要的。




示例说:我们在对象中有一个工资上限:

  int salary = 0; 
int salaryCap = 1000;

创建过程中,您可以验证已通过的工资金额:

  public Employee(int salary){
if(salary> = this.salaryCap)
this.salary = salary;
}




  • 类关系还决定是否要验证值是否。如果参数将传递给继承链,例如,我将花费时间验证它们,特别是如果它们将影响继承链中其他对象的状态。



示例:



每当我调用超级构造函数,我都试图验证输入:

  public Employee(int salary){
super(salary); //验证已知约束的工资
}




  • 变数来自哪里?如果您不信任源代码(如sql参数等),那么您应该在执行其他代码之前验证它们并可能对输入进行清理。这样可以防止安全攻击。


  • 我总是厌倦在构造函数中进行验证和参数检查。我更喜欢getter和setter来验证输入。这样,如果在创建对象时发生了某些事情,至少我有一个半工作对象的保证,而不是完全不一致的对象,其状态不能轻易确定。当然这取决于你的上下文,如果约束是严格的,你可以停止对象创建并提示客户端(用户,调用对象等)的有效输入参数。




    • 使用getter / setter给我的优势是,对象是通过调用对象给出的外部接口来逐步实现的,除了在创建期间约束验证,当出现异常时,会使对象不可用/不稳定。



      所以不是这样:

        public Employee(int salary){
      if(salary> = this.salaryCap)
      this.salary = salary;
      }

      我喜欢这个:

        public class Employee {
      public void setSalary(int salary){
      if(salary> = this.salaryCap)
      this.salary =薪水;
      }
      }

      后者使我有能力干净地退出调用者的有效异常,这不会影响对象创建(我不喜欢在构造函数中抛出异常)。



      简而言之,你的变量有约束吗?如果是,请在将它们设置为内部数据属性之前验证这些约束。


      I am creating a web application following the MVC pattern.

      In effective Java the author mentions to validate the parameters in the constructor of the class when creating a new object.

      However i am not creating some API that will be used by third parties. My classes just accept parameters from input fields of a form which are validated before beeing submited to the server.

      So in this case should i create my classes the way the author mentions in Effective java or it is useless?

      解决方案

      It is not as clear cut as reading a book and implementing what it says. You need to think and apply the knowledge to your specific situation.

      It really depends on how you are initializing the variables in your class and using them right after object construction:

      Some pointers:

      • If the variables are going to be used by some methods in the class or the object is going to be re-used right after constructions (which in most cases will), you should validate that the values that are required are not empty or null, to avoid getting nasty exceptions.

      • The second time to validate input parameters is when you expect the correct values to be set to specific internal variables. If you require that a parameter be constrained to a specific value range, then it is important that you validate.

      Example:

      Say we have a salary cap in the object:

      int salary = 0;
      int salaryCap = 1000;
      

      During creation, you can validate the passed in salary amount:

      public Employee(int salary) {
       if(salary >= this.salaryCap)
        this.salary = salary;
      }
      

      • The class relationship also determines whether you want to validate the values or not. If the parameters will be passed up the inheritance chain for-example, I would take the time to validate them, especially if they will affect the state of other objects in the inheritance chain.

      Example:

      Whenever I have to call the super constructor, I am tempted to validated the input:

      public Employee(int salary) {
       super(salary); //validate salary against known constraints
      }
      

      • Where are the variables coming from? If you do not trust the source (like sql parameters etc), then you should validate them and possibly sanitize the input before executing further code. This prevents security attacks.

      • I am always weary to do validation and parameter checking in the constructor. I prefer to have getters and setters to validate input. That way, if something happens at object creation, at least I have the guarantee of semi-working object than a complete inconsistent object whose state cannot be readily determined. Of course this depends on your context, if you constraints are strict, you can stop the object creation and prompt the client (user, calling object etc) for valid input parameters.

      The advantage that using getters/setters affords me is that the object is really constructed step by step by calling on the external interface the object gives, other than constraining the validation during creation, which when an exception occurs, renders the object unusable/unstable.

      So instead of this:

      public Employee(int salary) {
       if(salary >= this.salaryCap)
        this.salary = salary;
      }
      

      I prefer this:

      public class Employee {
       public void setSalary(int salary) {
        if(salary >= this.salaryCap)
            this.salary = salary;
       }
      }
      

      The latter gives me the ability to cleanly exit with a valid exception to the caller, which will not affect object creation (I don't like throwing exceptions in the constructor).

      In a nutshell, do your variable have constraints? If yes, validate those constraints before setting them to internal data properties.

      这篇关于我应该在构造函数中验证参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆