Hi @PavelM,
Welcome to our community!
return;
terminates the method immediately. While your code is correct, it is not regarded as “simpler” but that’s a matter of habit. In this particular case, both variants are perfectly fine. However, if there was more code in the method block, many programmers would prefer the first variant because, for us humans, it translates to “if this is true, the rest is irrelevant. No need to read further”. No return;
instruction indicates that there might be more code in the method block. We would have to skim the entire method block to see if the method executes any code if damageDealer
was false.
void DoSomething()
{
if (condition) { return;}
if (condition2)
{
// code
}
// more code
}
void DoSomething()
{
if (condition) {
if (condition2)
{
// code
}
// more code
}
}
void DoSomething()
{
if (condition) {
if (condition2)
{
// code
}
}
//more code
}
Does that make sense?
See also: