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 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;
   }
}

最佳答案

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

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

创建任何非法的 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;
}

再次声明,断言仅用于调试,您不应该 try catch 它们。任何断言异常都表明您的程序中存在错误(或断言语句中的错误)。

因此不应使用以下内容:

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);

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

关于java - 使用断言来测试前提条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18167641/

相关文章:

java - 有人怎么会意外地在 Java 中启动一个类呢?

java - 按数字顺序排列文件

java - 如何在 GWT 客户端生成 JSON 字符串?

java - Vaadin,子弹出窗口打开时禁用父窗口?

oop - Map 和 SortedMap - 冗余方法声明

java - 在 targetSdkVersion 设置为 31 或 android 12 后,telephonyManager.listen 不起作用

java - 使用 Spring MVC 提供 sitemap.xml 和 robots.txt

java - Android 以编程方式向工具栏添加按钮

java - 在 Android 中呈现的图像上的锯齿状边缘

java - 在 Java 中扩展 Serializable 类时,我为 serialVersionUID 选择什么重要吗?