java - 如何应对历史敏感性?

标签 java oop maintainability

所以我编写了一个Java程序,其中有一个函数handInExam(),该函数不能连续调用两次,因此该程序是历史敏感的。那么出现的问题是我需要一个变量canHandInExam来检查这个方法是否已经被调用,并在每个方法中更新这个变量,这导致可维护性非常差。下面是显示问题的代码片段。

public class NotAllowedException extends Exception {
    public NotAllowedException(String message) {
        super(message);
    }
}


import java.util.Scanner;


public class Exam {

    String[] exam;
    String[] answers;
    boolean canHandInExam;

    public Exam(String[] questions) {
        exam = questions;
        answers = new String[exam.length];
        canHandInExam = false;
    }

    // This method may only be called once in a row
    public void handInExam throws NotAllowedException() {
        if (canHandInExam) {
            // Send exam to teacher
            canHandInExam = false;
        } else {
            throw new NotAllowedException("You may not hand in this exam!");
        }
    }

    public void otherMethod() {
        // Do something
        canHandInExam = true;
    }
}

在这个小示例中,稍微调整每种方法是可行的,但是如果您有很多方法,则需要调整所有方法。由于在完成所有这些方法之后,您可能会再次调用 handInExam(),因此变量 canHandInExam 需要设置为 true

有没有一种方法可以以更易于维护的方式解决这个问题?我对其他可能的非面向对象的编程语言持开放态度,但目前我不确定什么是合适的。 我考虑过使用函数式编程(例如 Haskell),因为这些语言对历史不敏感,但是我不知道如何限制您只能连续调用一个函数一次。我尝试搜索如何在 Java 和 Haskell 中将函数调用限制为连续 n 次,但这最终只涉及如何调用函数 n 次。

最佳答案

如果您谈到提交考试,这并不意味着该考试已经完成,而是表示考试是针对某个实体进行的。因此,与其在考试中存储是否已提交或可以提交,类似这样的内容会更合适:

//or whatever you call this
public interface Institution {

    void handInExam(Exam exam) throws DuplicateExamException;

    boolean isHandedIn(Exam exam);

}

Institution 的实现存储已提交的考试(可能使用 Set)。

关于java - 如何应对历史敏感性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47572524/

相关文章:

java - Spring Boot 中每 t 的请求数限制

java - 如何在系统应用程序的棉花糖中无需用户交互即可授予权限?

c++ - 调用子类函数

C#多形式编码实践

java - 是否可以不使用预览布局的相机应用程序?

java - Spring Boot 。 ModelAndView addObject 不是替换标签

c++ - 如何在虚方法上使用模板参数类?

php - PHP 中的 ORM 框架是如何构建的?

performance - 一个数据库还是多个数据库?

javascript - 在 JavaScript 中编写多行字符串最简洁的方法是什么?