Mahesh Mahesh - 15 days ago 8
C# Question

Which design is the best for this scenario?

Can anyone tell me which design is the best for this scenario?

I have classes called

BasicAccount
,
SavingAccount
and
CurrentAccount
.

SavingAccount
and
CurrentAccount
should have all the features of
BasicAccount
. Later it might be the case that we may introduce a new Account called
AdvanceAccount
, it should have all the features of
CurrentAccount
and
SavingAccount
. How should I design the structure?

My answer:


  • lets keep
    BasicAccount
    as abstract,
    SavingAccount
    is also abstract, and implements
    BasicAccount

  • Create one interface
    ICurrentAccount
    and currentaccount implements
    BasicAccount
    and
    ICurrentAccount
    ,

  • If we have
    AdvanceAccount
    then implement it with
    SavingAccount
    and
    ICurrentAccount
    .



Is there any better way? This was asked to me in an interview and the interviewer was not satisfied with my answer I guess.

Answer

I'd use something like this:

abstract class BasicAccount {}

interface ISavingAccount {}
interface ICurrentAccount {}

class SavingAccount : BasicAccount, ISavingAccount {}  
class CurrentAccount : BasicAccount, ICurrentAccount {}  
class AdvanceAccount : BasicAccount, ISavingAccount, ICurrentAccount {}  

If SavingAccount and CurrentAccount have a lot of functionality, you can use aggregation in AdvanceAccount implementation:

class AdvanceAccount : BasicAccount, ISavingAccount, ICurrentAccount 
{
    private readonly SavingAccount savingAccount;
    private readonly CurrentAccount currentAccount;

    public AdvanceAccount()
    {
        savingAccount = new SavingAccount(...);
        currentAccount = new CurrentAccount(...);
    }

    // redirect ISavingAccount and ICurrentAccount implemetation
    // to savingAccount and currentAccount respectively
}  

UPD.
Note, that direct instantiation of SavingAccount and CurrentAccount in AdvanceAccount is just a sample. IRL you probably will use IoC container.

Comments