user2603796
user2603796

Reputation:

Should i use instanceof in this scenario or i need to use polymorphism

Suppose I have an Account class,

public class Account {
   void Print();
}

and I have derived two subclasses from it i.e. SavingsAccount and CheckingAccount.

public class SavingsAccount extends Account{
   void Print();
}

public class CheckingAccount extends Account{
   void Print();
}

Now suppose I have a driver class lets say SimulateAccounts which has an array list of type Account,

public class SimulateAccounts{
   ArrayList<Node> myAccounts = new ArrayList<Node>();
   void simulate()
   { //suppose some function has added added 5 savingAccounts and 10 checkingsAccounts in myAccounts arraylist

   }

Now my question is that I want to find the count of the type savingAccounts and checkingAccounts in arraylist myAccounts in the above function of simulate, I can do this by using instanceof function. But I am confused over using it as I have read on numerous places that using instanceof is bad practice and code smell, so how can I fit polymorphism into it to avoid using instanceof or is it ok to use. Moreover if I use instance of and in future name of savingsAccount changes I need to also update my this code in simulation function! So what should I do here. Thanks

Upvotes: 0

Views: 127

Answers (2)

ortis
ortis

Reputation: 2223

You could use enum to avoid instanceof:

public enum AccountType
{
   Check, Saving
}


public class Account 
{
   void Print();
   AccountType getAccountType();
}

public class SavingsAccount extends Account
{
  void Print(){};

  AccountType getAccountType()
  {
     return AccountType.Saving;
  }
}

public class CheckingAccount extends Account
{
  void Print(){};

  AccountType getAccountType()
  {
     return AccountType.Check;
  }
}

Now, if you want to know the type of an Account instance:

Account a = ...

switch(a.getAccountType())
{
 case Check:
   // do something specific to checking account
   break;

 case Saving:
   //do something specific to saving account
   break;

 default:
   break;
}

BTW, the use of extends to inherits classes is even worse than using instanceof in my opinion.

Upvotes: 0

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44449

If you're using C# (your naming conventions indicate both Java and C#), you can just use .OfType<CheckingAccount>().Count.

But sure, go ahead and use instanceof. This isn't why it should be used with caution, it's when you define subclass-specific behaviour without providing an implementation in the class itself.

For example:

if(account instanceof CheckingAccount)
{
    // Do something
} else if(account instanceof SavingsAccount) {
    // Do another thing
}

As opposed to

account.DoAccountTypeSpecificThing();

What you want to do makes sense.

Upvotes: 1

Related Questions