I am trying to understand this code snippet:
class Worker
{
public bool DoThisJob(string job, int numberOfShifts)
{
if (!String.IsNullOrEmpty(currentJob))
return false;
for (int i = 0; i < jobsICanDo.Length; i++)
if (jobsICanDo[i] == job)
{
currentJob = job;
this.shiftsToWork = numberOfShifts;
shiftsWorked = 0;
return true;
}
return false;
}
}
If this if
statement has more then one line of code (including the for
loop and the two return
s), why doesn't it have curly braces?
One-line statement Well if there is only one statement to execute after if condition then using curly braces or not doesn't make it different. Without curly braces only first statement consider in scope so statement after if condition will get executed even if there is no curly braces.
If there is only one statement for the if condition, curly braces are optional but if there are a series of steps curly braces are mandatory. That being said, you always want to keep the option of adding more statements to an if condition later. It is more readable and reduces error or bugs.
Java has a "feature" which allows you to omit curly brackets when writing if statements, for loops, or while loops containing only a single statement. You should never use this feature – always include curly brackets. The reason for this is because omitting curly brackets increases your chances of writing buggy code.
The code is equivalent to this:
class Worker
{
public bool DoThisJob(string job, int numberOfShifts)
{
if (!String.IsNullOrEmpty(currentJob))
{
return false;
}
for (int i = 0; i < jobsICanDo.Length; i++)
{
if (jobsICanDo[i] == job)
{
currentJob = job;
this.shiftsToWork = numberOfShifts;
shiftsWorked = 0;
return true;
}
}
return false;
}
}
Only the next statement is part of the if when there are no curly brackets. For the for
loop, the if
is the next statement, so everything is included with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With