Replace Conditional Statements (IF/ELSE or SWITCH) With Polymorphism
My Objective here is to let you guys know that if we have lot of conditional statements in our code, how we can remove them by using OOPS concepts.So to explain that I have taken a very simple problem statement.
Problem: Based on different kind of game objects, we want to increase the score differently.
Interface GameObject(){ }
class Ship implements GameObject {}
class Station implements GameObject {}
class Commet implements GameObject {}
Solution via If/else:
So to achieve that what We have a handler class and we have increase points method, which will increase different points based on the object that we will pass.
class Handler
{
public void increasePoints(GameObject go1)
{
if(typeOf(go1)== Ship )
{
//increase points by 5
}
else if(typeOf(go1)==Station)
{
//increase points by 10
}
else if(typeOf(go1)==Commet)
{
//increase points by 15
}
}
}
We will right the code something like this.
Now just think as soon as the number of objects will keep on increasing, managing this type of code will be a nightmare .
Now to solve above problem what we will do? how we will remove all if conditions from here?
To do that we have to first understand that we need to remove the increasing point logic out of handler and put it in respective game objects.
By doing so, we can let individual objects to take care of their increasing points logic. See below:
Interface GameObject(){
increasePoints(points){};
}
class Ship implements GameObject {
increasePoints(points){
//increase points by 5
}
}
class Station implements GameObject {
increasePoints(points){
//increase points by 10
}
}
class Commet implements GameObject {
increasePoints(points){
//increase points by 15
}
}
class Handler {
public void increasePoints(GameObject go1) {
go1.increasePoints(points);
}
}
See Now handler code is so simplified and all logic moves to the corresponding class and there is no if else condition .
**** Since each object is having only one method , we can also use lambda here, Write in the comments if you want to know, how to handle this by using lambda.****
Thank you. But I still have to write:
Handler myHandler;
if ( clicked ship )
myHandler= new Ship();
else if ( clicked station )
myHandler= new Station ();
else ( clicked commet )
myHandler= new Commet ();
myHandler.increasePoints
How do I remove these if-else/ switch?
I agree with t f. How do we actually get rid of the if else clause?
You don’t have to …Just create handler of GameObject and call increase point …it willl figure out which object it is …and call the corresponding increasePoints method.
Isn’t it still necessary to determine which child of GameObject as the question states? I can see using a map with keys to eliminate the “if” statements. But without something like that, it seems that the issue has just been pushed to a different layer.
would like to know how to handle this by using lambda