vendredi 23 novembre 2018

Refactor if statement where i have to initialize different object

i'm searching the smartest way of handle this method

public boolean addAccount(String cf, AccountType type) {
    String iban = name + cf;
    if (bankAccounts.containsKey(iban)) return false;
    if (type.name().equals("CHECKINGACCOUNT")) {
        CheckingAccount cc = new CheckingAccount(cf, iban, 0);
        bankAccounts.put(iban, cc);
        return true;
    }
    if (type.name().equals("DEPOSIT")) {
        DepositAccount cd = new DepositAccount(cf, iban, 0);
        bankAccounts.put(iban, cd);
        return true;
    }
    if (type.name().equals("WEB")) {
        WebAccount cw = new WebAccount(cf, iban, 0);
        bankAccounts.put(iban, cw);
        return true;
    }
  return false;
}

AccountType is enum that contains (DEPOSIT,WEB,CHECKINGACCOUNT); bankAccounts is an HashMap that contains iban (key) & CheckingAccounts OR DepositAccount OR WebAccount; CheckingAccounts ,DepositAccount,WebAccount are 3 classes that inherit an abstract class called Account.

I'm trying to substitute the if with an HashMap that check the key (Type of account) with the String insert by the user and instantiates one of the three class associated to the key in the HashMap. The problem is that i can't create the correspondence between the String and the Account because i need to instantiate that (but i don't know the cf in that moment)

Could someone show me some better way to manage it?

Aucun commentaire:

Enregistrer un commentaire