Is using too many 'if' statements bad programming?

user5187524 picture user5187524 · Nov 26, 2015 · Viewed 20.4k times · Source

I am curious as to if I am using too many if/else if statements. I am writing a tic-tac-toe program using javascript, and to determine if the computer should block the player I am using about 9 if statements and I use about 9 when determining if there is 3 in a row.

For example:

if(r1c1V === xOrO && r1c2V === xOrO && r1c3V === xOrO)
{
    is3InARow = true;
}
else if(r2c1V === xOrO && r2c2V === xOrO && r2c3V === xOrO)
{
    is3InARow = true;
}
else if(r3c1V === xOrO && r3c2V === xOrO && r3c3V === xOrO)
{
    is3InARow = true;
}
.
.
.
.

and so on.

So my question is, am I using too many if statements? or is there no better way to do this? My friend was telling me that I shouldn't really use that many if statements, but I am not sure if he is true or not, I can understand why in some cases that it would be slower or bad, but I am not sure.

Thanks in advance!!

Answer

OliverRadini picture OliverRadini · Nov 26, 2015

This is rather subjective, so is not really ideal for Stack Overflow.

What your friend is probably suggesting is that programs which use long if/else statements, nested ifs etc. are sometimes difficult to maintain, and are not always very readable. You can sometimes replace long if statements with a separate function, which can be much easier to maintain.

For instance in tic-tac-toe:

function checkRow(rowToCheck){
    if (rowToCheck[0] === rowToCheck[1] && rowToCheck[1] === rowToCheck[2]){
        return true;
    } else {
        return false;
    }
}

Not to say that is perfect or even good code, but you can see how it would allow you to reduce the number of if statements in your code. It could be factored further:

function checkRow(rowToCheck){
    var allMatch = true;
    for (var i=0;i<rowToCheck.length && allMatch;i++){
        allMatch = rowToCheck[i] === rowToCheck[0];
    }
    return allMatch;
}

That allows for rows of varying length, and cuts down of the if statements. Anyway I hope that explains some of the ways you can remove if statements.


Edit

Further in the future, I'd suggest that there is yet another, better way to check the equality of the elements in a row:

const o = 'o'
const x = 'x'

const rows = [
  [o, x, x],
  [x, x, x],
  [o, o, x]
]

const rowIsEqual = row => !row
  .some(square => square !== row[0])
  
const results = rows.map(rowIsEqual)
  
console.dir(results)