【问题标题】:Issues with validating fields in constructor of a subclass在子类的构造函数中验证字段的问题
【发布时间】:2018-06-24 16:25:54
【问题描述】:

我现在正在学习 Java 的继承。我总共有3个问题,感谢您的支持。

第一个问题:我可以在其构造函数中验证类的字段吗?

第二个问题:有人建议我抛出异常进行验证。是指向调用者方法抛出异常还是抛出异常并在构造函数内部处理?

第三个问题:假设该类不是子类,我可以验证代码中显示的字段,而不是使用异常吗?(假设代码不会因为 super() 而产生错误)。

子类

import javax.swing.JOptionPane;

public class Essay extends GradedActivity
{
   private final double MAXGRAMMAR = 30; 
   private final double MAXSPELLING = 20;   
   private final double MAXLENGTH = 20;
   private final double MAXCONTENT = 30;   

   private double grammar;
   private double spelling;
   private double length;
   private double content;


public Essay(double grammar, double spelling, double length, double content)

  {
      double total;

  while(grammar < 0 || grammar > MAXGRAMMAR)
  {
     grammar = Double.parseDouble(JOptionPane.showInputDialog(null, "Invalid grammar value, try again: "));
     this.grammar = grammar;
  }
  while(spelling < 0 || spelling > MAXSPELLING)
  {
     spelling = Double.parseDouble(JOptionPane.showInputDialog(null, "Invalid spelling value, try again: "));       
     this.spelling = spelling;
  }
  while(length < 0 || length > MAXLENGTH)
  {
     length = Double.parseDouble(JOptionPane.showInputDialog(null, "Invalid length value, try again: "));      
     this.length = length;

  }
  while(content < 0 || content > MAXCONTENT)
  {
     content = Double.parseDouble(JOptionPane.showInputDialog(null, "Invalid content value, try again: "));      
     this.content = content;
  }

  total = grammar + spelling + length + content;
  super(total);               
   }
};

超类

/**
   A class that holds a grade for a graded activity.
*/

public class GradedActivity
{
   private double score;  // Numeric score

   /**
      The setScore method sets the score field.
      @param s The value to store in score.
   */

   public void setScore(double s)
   {
      score = s;
   }

   /**
      The getScore method returns the score.
      @return The value stored in the score field.
   */

   public double getScore()
   {
      return score;
   }

   /**
      The getGrade method returns a letter grade
      determined from the score field.
      @return The letter grade.
   */

   public char getGrade()
   {
      char letterGrade;

      if (score >= 90)
         letterGrade = 'A';
      else if (score >= 80)
         letterGrade = 'B';
      else if (score >= 70)
         letterGrade = 'C';
      else if (score >= 60)
         letterGrade = 'D';
      else
         letterGrade = 'F';

      return letterGrade;
   }
}

【问题讨论】:

    标签: java validation inheritance constructor


    【解决方案1】:
    1. 是的,您可以在构造函数中进行验证。
    2. 您可以在这里做两件事。要么不要让用户通过抛出异常来创建具有无效值的对象并让调用者处理异常,要么在提供错误输入时定义默认值。第二个选项可能在某些情况下有效。抛出异常并在那里处理没有多大意义,这几乎就像检查条件并在 else 块中处理它一样。
    3. 没有什么可以阻止您在代码中执行您正在执行的操作,但作为一种良好的编码实践,用户输入是视图的一部分,您可以创建一个视图,允许您输入所需的值并在表单上进行验证一旦所有字段都有效,将其传递给构造函数。这样一来,构造函数就不会为每个无效条目提供一次性输入对话框,而只是烦恼因素。

    【讨论】:

      【解决方案2】:

      您可以按照自己的要求去做,但这不是一个好的建议。

      如果您希望您的代码可维护、可重用、可扩展,并且您可以轻松地在其他技术中实现它。保持“高内聚低耦合”类的基本概念。

      类只是一个简单的对象(Pojo)。保持构造函数清洁:

      Public Essay (Type value){
          this.value=value;
      }
      

      默认保留 Gets 和 Sets。

      现在,当您必须创建这些 pojo 时,请在创建对象之前执行检查。

      你总是有一个类来创建 Pojo (Object) Normaly 构造函数:

      if(validations(fields))
            Abstract class = new ConcreteClass(fields);
      else throw new ServiceException("Your exception");
      

      所以你的答案是:

      第一个问题:我可以在其构造函数中验证类的字段吗?

      可以,但不建议在构造函数中添加逻辑。

      第二个问题:有人建议我抛出异常进行验证。是指向调用者方法抛出异常还是抛出异常并在构造函数内部处理?

      应始终管理异常,将其保持在可控范围内 带有属性消息的环境,通常您创建一个客户 例外:

      public class ServiceException extends RuntimeException {
          private static final long serialVersionUID = 1L;
          public ServiceException(String message) {
              super(message);
          }
      }
      

      第三个问题:假设该类不是子类,我可以验证代码中显示的字段,而不是使用异常吗?(假设代码不会因为 super() 而产生错误)。

      如果您不想在创建对象之前验证文件,您可以在创建对象之后使用自定义方法,例如 -> ConcreteClass.validateFields()

      将您现在对构造函数进行的验证添加到您的自定义方法 (validateFields()) 中,您将获得结果。

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-02
        • 2015-03-30
        相关资源
        最近更新 更多