In general, it’s considered not to be a good practice to have if
statements by some type attribute or by instanceof
checks.
An alternative to this is the visitor pattern. Here’s a sketch of what you could do:
interface IAccount {
void process(AccountProcessor processor);
}
interface AccountProcessor {
void processBasicAccount(Account acc);
void processCustomerAccount(CustomerAccount acc);
void processAdminAccount(AdminAccount acc);
}
The idea is that you have an interface that defines a process
method for all the accounts, that receives an AccountProcessor
(you can change the names here, this is just to show an example). There should be one method for every different type of account. You could even use method overloading, i.e. all methods could be named something like processAccount
and receive a specialized account type.
Now, your Account
class and all its subtypes should implement the IAccount
interface:
class Account implements IAccount {
@Override
void process(AccountProcessor processor) {
processor.processBasicAccount(this);
}
// all the other Account stuff
}
class CustomerAccount implements IAccount {
@Override
void process(AccountProcessor processor) {
processor.processCustomerAccount(this);
}
// all the other CustomerAccount stuff
}
class AdminAccount implements IAccount {
@Override
void process(AccountProcessor processor) {
processor.processAdminAccount(this);
}
// all the other AdminAccount stuff
}
Now, with all these pieces in place, you are ready to process your list of accounts:
class AccountProcessorImpl implements AccountProcessor {
private List<Account> accounts; // filled with all the accounts
void doSomethingWithAllTheAccounts() {
// iterate all the accounts and process each one of them
accounts.forEach(IAccount::process);
}
@Override
public void processBasicAccount(Account acc) {
// do something with the basic account
}
@Override
public void processCustomerAccount(CustomerAccount acc) {
// do something with the customer account
}
@Override
public void processAdminAccount(AdminAccount acc) {
// do something with the admin account
}
}
I hope you grasp the general idea. This is just a sketch to show you the core technique. There might be variants, i.e. you might have separate processors for each different type of account, or you might process the list of accounts in a class other than the AccountProcessorImpl
, etc.
CLICK HERE to find out more related problems solutions.