gpt4 book ai didi

Java:方法/构造函数参数验证。还应该进行多次验证调用吗?

转载 作者:行者123 更新时间:2023-12-01 20:02:05 24 4
gpt4 key购买 nike

我有一个关于验证方法/构造函数参数的问题。

假设我有一个类BankAccount。该类在构造函数中执行一些基本验证(注意:这不是我实现此类的方式,最好使用多态性和接口(interface)实现来提供不同类型的银行帐户。这里是一个枚举 BankAccount.使用类型)。

BankAccount(Type type, double balance, String ownerName, String accountNumber) {
// Make sure no invalid arguments are passed.
if (type == null) {
throw new IllegalArgumentException("'type' may not be null!");
}
if (balance < type.getBalanceLimit()) {
throw new IllegalArgumentException("initial 'balance' may not be less than the accounts balance limit!");
}
if (ownerName == null || ownerName.trim().isEmpty()) {
throw new IllegalArgumentException("'ownerName' may not be null or empty!");
}
if (!type.requiresOwner()) {
throw new IllegalStateException("Cannot create an account with an owner if that account type does not require an owner!");
}
if (accountNumber == null || accountNumber.trim().isEmpty()) {
throw new IllegalArgumentException("'accountNumber' may not be null or empty!");
}

this.type = type;
this.balance = balance;
this.ownerName = ownerName;
this.accountNumber = accountNumber;
}

首先:这是验证构造函数参数时的方法,还是最好先设置所有字段,然后调用方法 validateState() 来检查构造状态是否有效否则抛出异常。像这样的事情:

BankAccount(Type type, double balance, String ownerName, String accountNumber) {
this.type = type;
this.balance = balance;
this.ownerName = ownerName;
this.accountNumber = accountNumber;

validateState();
}

以上解决方案中哪一种更可取(在大多数情况下)?

我的问题的第二部分是关于重复验证。假设我有一个类Bank。此类有一个方法 createGiroAccount(Account.Type type, String OwnerName)

/**
* Creates a new {@link Account} of the specified {@link Account.Type} for the given owner.
* Note that the {@link Account.Type} must be a giro account type.
*
* @param type the type of the new account which must be one of the available giro options, not null
* @param ownerName the owner´s name who owns the new account, not null or empty
*/
public void createGiroAccount(BankAccount.Type type, String ownerName) {
// Really basic validation
if (type == null || !type.isGiro()) {
throw new IllegalArgumentException("'type' may not be null and must be of type giro!");
}
if (ownerName == null || ownerName.trim().isEmpty()) {
throw new IllegalArgumentException("'ownerName' may not be null or empty");
}

String accountNumber = generateUniqueAccountNumber();
accounts.add(new BankAccount(type, ownerName, accountNumber));
}

我的问题:是否也应该对参数进行验证,即使 BankAccount 无论如何都会验证参数/状态?

最佳答案

Is this the way to go when validating constructor arguments or is it preferable to set all the fields first and then call a method validateState()

您可以创建custom annotation如果您不想编写重复的代码,请检查参数的有效性。

The 2nd part of my question is about repeated validation.

如果您只有一个构造函数,则不需要在 createGiroAccount 中进行检查。否则你就会这样做。

关于Java:方法/构造函数参数验证。还应该进行多次验证调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47920583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com