Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Why is it bad to use multiple if statemets when it's for the same statement?

At the end of the video he explained that using or statments makes your code less repeating. This is of course good and i already knew this but why is it bad other than the if-statements taking up multiple lines of code and making it look more sloppy, does it have an impact on the program's execution speed for example?

Link to course: https://teamtreehouse.com/library/censoring-words-using-logical-ors#questions

1 Answer

saykin
saykin
9,835 Points

It's two part I would say. One for readability, making your code easier to read and understand. There is also the part where if you have one if statement with several conditions, your code could execute faster.

Example:

// Example one
If (bool1 && bool2 && bool3) {
  // Do something
}

// Example two
If (bool1) {
  // Do something
}

If (bool2) {
  // Do something
}
If (bool3) {
  // Do something
}

// Example three
If (bool1 || bool2 || bool3) {
  // Do something
}

In the first example, say the first bool is already false, the Java compiler can already stop checking the if and move on. While in example two, it will check each and every statement, using more time and potentially making your app slower (This is relevant for much larger projects). The same idea for example one can be applied to example three, if the first statement is true, the Java compiler can skip checking the other conditions and execute the code inside the if statement.

I hope this explanation made it a bit more clear on why you are encouraged to use more conditions rather than if statements, especially in Craig's example of blocking bad words.

Thank you for the helpful answer, this clears up the small things I was wondering about if-statements.