DDD Approach to Access External Information

The first thing I noticed was the improper use of the bank account factory. The factory, pretty much as you have it, should be used by the repository to create the instance based on the data retrieved from the data store. As such, your call to accountRepository.FindByID will return either a FixedBankAccount or SavingsBankAccount object depending on the AccountType returned from the data store.

If the interest only applies to FixedBankAccount instances, then you can perform a type check to ensure you are working with the correct account type.

public void IssueLumpSumInterest(int accountId)
{
    var account = _accountRepository.FindById(accountId) as FixedBankAccount;

    if (account == null)
    {
        throw new InvalidOperationException("Cannot add interest to Savings account.");
    }

    var ownerId = account.OwnerId;

    if (_accountRepository.Any(a => (a.BankUser.UserId == ownerId) && (a.AccountId != accountId)))
    {
        throw new InvalidOperationException("Cannot add interest when user own multiple accounts.");
    }

    account.AddInterest();

    // Persist the changes
}

NOTE: FindById should only accept the ID parameter and not a lambda/Func. You’ve indicated by the name “FindById” how the search will be performed. The fact that the ‘accountId’ value is compared to the BankAccountId property is an implementation detail hidden within the method. Name the method “FindBy” if you want a generic approach that uses a lambda.

I would also NOT put AddInterest on the IBankAccount interface if all implementations do not support that behavior. Consider a separate IInterestEarningBankAccount interface that exposes the AddInterest method. I would also consider using that interface instead of FixedBankAccount in the above code to make the code easier to maintain and extend should you add another account type in the future that supports this behavior.

Leave a Comment