當涉及多個聚合時,我懷疑域應該如何執行業務規則。域驅動設計:服務和聚合中的域規則
假設我有帳戶和外部帳戶聚集:
public class Account {
public String getId() {...}
public void add (Double amount) {}
}
public class ExternalAccount {
public String getId() {...}
public void add (Double amount) {}
}
這個服務:
public class TransferService implements TransferServiceInterface {
public void transfer (String AccountId, String ExternalAccountId, Double amount) {
Account fromAccount = accRepository.get(AccountId);
ExternalAccount toAccount = extAccRepository.get(ExternalAccountId);
transferIsValid(fromAccount, toAccount, amount);
fromAccount.add(-amount);
toAccount.add(amount);
}
}
transferIsValid將拋出一個異常,如果轉讓不符合域規則的規定。
我怎樣才能防止這種模式的用戶從沒有使用服務,並執行這樣的事情:
Account fromAccount = accRepository.get(AccountId);
ExternalAccount toAccount = extAccRepository.get(ExternalAccountId);
fromAccount.add(-amount);
toAccount.add(amount);
用戶沒有使用這項服務並沒有使用transferIsValid(... )來檢查完整性。我相信我的設計中存在一個錯誤,因爲用戶不應該能夠做一些無效的事情。我怎樣才能防止它?我的設計中的錯誤在哪裏?
這是什麼意思「用戶」在這裏,用戶如何調用上面列出的代碼而不調用服務? –
當我提到「用戶」時,我指的是使用該域的開發人員。開發人員可能決定不使用該服務,並直接使用聚合。除了代碼重複之外,不保證開發人員會執行業務規則。 – Pleonc
爲什麼開發者可能決定在他們自己創建這些服務時不使用這些服務? –