0

I have a code (Java for example):

    boolean A(...){
       if (...) return true;
       else return false;
    }

    void C(...){

       if (A) {doSomeThing();}
       else {doNothing();}
    }

But logic is changed and today i need return 3 cases. It look something like this

        int A(...){
           if (...){ return int;}
           else {
              if (...) {return int;}
              else {return int;}
           }
        }

        void C(...){

           if (A == 1) {doSomeThing1();}
           if (A == 2) {doSomeThing2();}
           if (A == 3) {doSomeThing3();}
        }

Is this a best practices or I should use something other instead of "int"? Or I should change my logic and divide it on two boolean? P.S. I know that this questions are fully but it disturbs me.

  • 2
    Use [`switch-case`](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html). – Maroun Nov 25 '13 at 12:49
  • Well, a good suggestion would require more information about what those methods do. For example, can it change in future to return more values? – Rohit Jain Nov 25 '13 at 12:49
  • For example, I have a textbox and handler for it that displays a warning "wrong quantity of symbols". But today i want display 3 types - "too more symbols", "too many" and nothing message. – Ann Savinovskikh Nov 25 '13 at 13:01
  • using three if checks for the same variable checking is definitely a bad practice , why suppose " A is 1" in that case "doSomeThing1()" will happen but still the code will go ahead and try 2 un needed IF checks . I would recommend Change to multiple if to "if else if " or switch case. – amIT Mar 13 '14 at 14:47

2 Answers2

7

Best practice would be to use enum type instead of boolean.

public enum PossibleValues {
  TRUE, FALSE, NEITHER;
}
user1455836
  • 752
  • 6
  • 18
4

Actually how many condition you should check is depends on your requirement. For that you can use if-else or swith-cases.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115