Friday, January 23, 2015

Use Polymorphism and code to Interface instead of if and elseif

if elseif else comes under procedural programming, When we talk about Object Oriented programming we need to escape out from if elseif else  until any primitive data type is using for.Means In Object Oriented programming if elseif else is used only for primitive data type not for objects.


Let talk about some simple example with if else and try to convert this if else to purely object oriented.

suppose you have two user say "GUEST" and "ADMIN", w.r.t to this userType  you have to write  some bussiness logic.Since i am java developer and i need to think about Object oriented programming not  procedural programming .

Firt's let go with  most familiar flow which basically maximum java developer follow to do task and what's that

String userType=""//it can be either Guest or Admin

if("guest".equalsIgnoreCase(userType)){
doGuestBussinessLogic();
}
else if("admin".equalsIgnoreCase(userType)){

doAdminBussinessLogic();
}else{

throwExceptionOrDoNothing();
}


In don't know  about other but i definitely say that we are writing C-program in java Syntax

Now Lets try this in Pure java language

public interface User {
    public void bussinessLogicofUser();
}

public class AdminUser implements User {

    @Override
    public void bussinessLogicofUser() {
        System.out.println("Admin user bussiness logic started");
       
    }

}

public class GuestUser implements User {

    public void bussinessLogicofUser(){
        System.out.println("Guest user bussiness logic started");
    }
   
}

public enum UserType {
ADMIN(new AdminUser()),GUEST(new GuestUser());
User user;

private UserType(User user) {
  this.user = user;
}

public User
getUserTypeInstance(){
  return this.user;
}
}


Now in Main method where we write if else,it's time to delete that if else and write object oriented program.Let see how
try{
UserType.valueOf(userType.toUpperCase()).getUserTypeInstance().bussinessLogicofUser();
}catch(IllegalArgumentException e){
throwExceptionOrDoNothing();
}
Early we have written approx 7 line of code and here only 1 line code did that work.
That's the using of Object Oriented Program