重构指南 - 为布尔方法命名(Rename boolean method)

时间:2023-03-09 22:23:58
重构指南 - 为布尔方法命名(Rename boolean method)

如果一个方法中包含多个布尔类型的参数,一是方法不容易理解,二是调用时容易出错。

重构前代码

 public class BankAccount
{
public void CreateAccount(Customer customer, bool withChecking, bool withSavings, bool withStocks)
{
// do work
}
}

重构后代码

public class BankAccount
{
public void CreateAccountWithChecking(Customer customer)
{
CreateAccount(customer, true, false);
} public void CreateAccountWithCheckingAndSavings(Customer customer)
{
CreateAccount(customer, true, true);
} private void CreateAccount(Customer customer, bool withChecking, bool withSavings)
{
// do work
}
}

重构后,将原来方法改为private防止外部调用,而暴露出命名良好的方法供调用。