Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improve Java code: too many if's

I have several cases and I am just using simple if ... if else blocks.

How can I reduce the number of if statements in this code?

Perhaps I could use a lookup table, but I am not sure how to implement it in Java.

private int transition(char current, int state)
{
    if(state == 0)
    {
        if(current == 'b')
        {
            return 1;
        }
        else 
            return 0;
    }
    if(state == 1)
    {
        if(current == 'a')
        {
            return 2;
        }
        else 
            return 0;
    }
    if(state == 2)
    {
        if(current == 's')
        {
            return 3;
        }
        else 
            return 0;
    }
    if(state == 3)
    {
        if(current == 'e')
        {
            return 3;
        }
        if(current == 'b')
        {
            return 4;
        }
        else 
            return 0;
    }
    if(state == 4)
    {
        if(current == 'a')
        {
            return 5;
        }
        else 
            return 0;
    }
    if(state == 5)
    {
        if(current == 'l')
        {
            return 6;
        }
        else 
            return 0;
    }
    else
        return 0;
}
like image 566
PFranchise Avatar asked Sep 05 '10 17:09

PFranchise


People also ask

How many nested IF is too many?

Excel has limits on how deeply you can nest IF functions. Up to Excel 2007, Excel allowed up to 7 levels of nested IFs. In Excel 2007+, Excel allows up to 64 levels. However, just because you can nest a lot of IFs, it doesn't mean you should.

How do you stop a long if-else statement?

Avoid using nested if-else statements. Keep the code linear and straightforward. Utilize creating functions/methods. Compare it when we try to use an if-else statement that is nested and that does not utilize the power of the return statement, We get this (Code 1.4).

How do you handle multiple if statements in Java?

When using multiple conditions, we use the logical AND && and logical OR || operators. Note: Logical AND && returns true if both statements are true. Logical OR || returns true if any one of the statements is true.


1 Answers

What you're trying to do looks very much like a finite state machine, and these are usually implemented with the help of a transition table. Once you set up the table, it's simply a matter of indexing to the position you want to get the return value. Assuming your return values are all less than 256, you can use a 2D byte array:

byte table[][] = new byte[NUM_STATES][NUM_CHARACTERS];
// Populate the non-zero entries of the table
table[0]['b'] = 1;
table[1]['a'] = 2;
// etc...

private int transition(char current, int state) {
  return table[state][current];
}
like image 151
casablanca Avatar answered Oct 16 '22 17:10

casablanca