Java 使用断言测试前提条件

Java 使用断言测试前提条件,java,Java,我正在做一项学校作业,我应该使用断言来测试存款方法和构造函数的先决条件。我想出了这个方法,但我一直在思考如何添加到构造函数中 以下是我到目前为止的情况: /** A bank account has a balance that can be changed by deposits and withdrawals. */ public class BankAccount { private double balance; /** Constructs

我正在做一项学校作业,我应该使用断言来测试存款方法和构造函数的先决条件。我想出了这个方法,但我一直在思考如何添加到构造函数中

以下是我到目前为止的情况:

/**
   A bank account has a balance that can be changed by 
   deposits and withdrawals.
*/
public class BankAccount
{  
   private double balance;

   /**
      Constructs a bank account with a zero balance.
   */
   public BankAccount()
   {   
      balance = 0;
   }

   /**
      Constructs a bank account with a given balance.
      @param initialBalance the initial balance
   */
   public BankAccount(double initialBalance)
   {   
      balance = initialBalance;
   }

   /**
      Deposits money into the bank account.
      @param amount the amount to deposit
   */
   public void deposit(double amount)
   {  
      assert amount >=0;

       double newBalance = balance + amount;
      balance = newBalance;
   }

   /**
      Withdraws money from the bank account.
      @param amount the amount to withdraw
   */
   public void withdraw(double amount)
   {   
      double newBalance = balance - amount;
      balance = newBalance;
   }

   /**
      Gets the current balance of the bank account.
      @return the current balance
   */
   public double getBalance()
   {   
      return balance;
   }
}
创建任何非法的
BankAccount
会立即导致异常(如果启用了断言)

断言几乎可以放在代码中的任何地方。它们用于调试目的,如果禁用它们(例如,在生产过程中),则不会产生任何效果

如果bankaccount的目的是始终为正值,则可能需要添加其他断言,例如:

/**
   Withdraws money from the bank account.
   @param amount the amount to withdraw
*/
public void withdraw(double amount)
{   
    assert amount <= this.balance;

    this.balance -= amount;
}
相反,您应该检查前提条件

BankAccount newbankaccount = new BankAccount(5);
if (newbankaccount.getBalance() < 6.0)
{
    // illegal withdrawal
}
else
    newbankaccount.withdraw(6.0);
BankAccount newbankaccount=新银行账户(5);
if(newbankaccount.getBalance()<6.0)
{
//非法提款
}
其他的
新银行账户提款(6.0);

只有当应用程序中存在逻辑错误时,才会触发断言异常。

Bas已经介绍了有关断言的重要部分。基本上,将在生产代码中跳过,但可以在调试期间启用

考虑到这一点,我将扩展银行帐户代码的行为,以实际使用常规Java if语句;因为存入负金额(或提取负金额)总是错误的。

我的2美分取决于何时使用

当您使用断言时,请不要将其与异常用法混淆

  • 检查私有/内部代码的前置条件、后置条件和不变量时使用断言

  • 使用断言向您自己或您的开发团队提供反馈

  • 在检查不太可能发生的事情时使用断言,否则这意味着应用程序中存在严重漏洞

  • 使用断言陈述你知道是真实的事情

  • 检查传递给公共或受保护方法和构造函数的参数时使用异常

请看这个:
希望这能有所帮助。

你能说得更具体一点吗?我不太确定你的问题是什么。你能提供更多的信息吗?对不起,我忘了提什么先决条件在哪里。存款方法要求存款金额至少为零。在BankAccount的构造函数中可能是“assert initialBalance>=0;”?为什么有四张向上投票?我的意思是,我可以看到一个,因为它有点完整,尽管在评论之前实际的问题是MIA,但是。。。拜托,我相信断言不是用来检查公共方法的参数的吧?我相信您已经在draw()方法中使用了它。它们不应该使用,但它们始终可以通过应用程序使用,以确保功能正确谢谢,我发现if语句更容易,但学校作业需要断言。@JoseM。为什么更容易?它们不那么冗长,可以关闭
if
语句可能更灵活,但它们实际上是用于不同的目的。@DaveNewton,对不起,这正是我想说的,更灵活。我不知道我可以使用断言而不是if语句来调试。这对我来说是一个新概念。我通常在VB上写,我不认为有什么类似于断言的东西。@DaveNewton我想知道你是否同意接受的答案。因为它有公共方法,所以参数使用了断言,oracle文档会说一些其他的东西。我只是想知道我是否遗漏了什么?@JNL OP的任务是专门使用断言,所以这是一个特例。断言而不是异常的问题在于,它们通常是关闭的,因此,如果在“现实生活”中可能出现错误,则应该使用异常。断言==内部和开发,异常==实际/可能发生。
try
{
    BankAccount newbankaccount = new BankAccount(5);
    newbankaccount.withdraw(6.0);
}
catch (Exception e)
{
    // illegal withdrawal
}
BankAccount newbankaccount = new BankAccount(5);
if (newbankaccount.getBalance() < 6.0)
{
    // illegal withdrawal
}
else
    newbankaccount.withdraw(6.0);
    public class BankAccount
    {  
        private double balance;

        /**
           Constructs a bank account with a zero balance.
        */
        public BankAccount()
        {   
            balance = 0;

            // assert is NOT used to validate params of public methods
            // if ( !isValidBalance(amount) ) {
            //     throw new IllegalArgumentException("Amount should be greater than zero.");
           // }

            //check the class invariant
            assert hasValidBalance(): "Construction failed.";

        }        
           // Implements the class invariant.
           // Perform all checks on the state of the object.
           // One may assert that this method returns true at the end
           // of every public method.

          private boolean hasValidBalance(){
              return balance>0;
          }
    }