如果一個方法中包含多個布爾類型的參數,一是方法不容易理解,二是調用時容易出錯。 重構前代碼 重構後代碼 重構後,將原來方法改為private防止外部調用,而暴露出命名良好的方法供調用。 ...
如果一個方法中包含多個布爾類型的參數,一是方法不容易理解,二是調用時容易出錯。
重構前代碼
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防止外部調用,而暴露出命名良好的方法供調用。