Is using too many 'if' statements bad programming?

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)

In general, yes, "too many" ifs are bad. Any problem can be solved just using ifs, but everything you see around you, functional programming, recursion, object modelling, is there to stop the if's getting out of control and leaving you with sprawling incomprehensible code. You should be more worried about the depth of nested ifs than the length of a sequence. Here's tic-tac-toe on rosetta code, if you want to see real cleverness.


Programming is all about automating processes. You will not hear me say that the way you are doing this is wrong. If it works then it is oke. But of course it would be more beautiful if you could find a way to make it check everything automatically. Like looping through all x cords and just check if all of those are checked. This may not be easier, but it will be more extendable. If you'd ever wish to play a game on a ten by ten grid. then you would only have to say that that is the size of the field. Right now you would need to add all those other lines of code.