Hi AJ,
honestly, I do not think there’s a right or wrong way to do it or a best practice. As long as the end result is as expected. I mean, there are some basic rules that you must, let’s say, obey (programming language specifics) but as far as your programming style, that is up to you. If you work alone, do it your way. If you work in a team, you should try and adopt some coding style from your team members and the team members from you.
Here are some examples from a project I was working on:
void AMainCharacter::AttackButtonPressedDown()
{
bAttackButtonPressedDown = true;
if (MovementStatus == EMovementStatus::EMS_Dead)
{
return;
}
if (!ActiveOverlapingItem)
{
if (EquippedWeapon)
{
Attack();
}
}
}
- In this case, I use the return statement because if the players movement state is “dead”, the rest of this function does not matter anymore.
The following code uses if-else if-return statement:
void AMainCharacter::Jump()
{
UAnimInstance* AnimInstance = GetMesh()->GetAnimInstance();
if (MovementStatus != EMovementStatus::EMS_Dead)
{
//Super::Jump();
if (AnimInstance && CombatMontage && EquippedWeapon)
{
AnimInstance->Montage_Play(CombatMontage, 2.0f);
AnimInstance->Montage_JumpToSection(FName("JumpEquiped"));
}else if (AnimInstance && CombatMontage && !EquippedWeapon)
{
AnimInstance->Montage_Play(CombatMontage, 2.0f);
AnimInstance->Montage_JumpToSection(FName("JumpUnequiped"));
} else
{
return; //Safety net, it will never trigger
}
}
}
- In this particular case, I do use the if - else if statement, and in the end I use an “catch statement” else return. Why I call it an catch statement? I find it important in an nested if-else if to use an final else statement to catch every other possible logical expression that you overseen. Like a safety net.
You can use it even for debugging: my last else could look like this:
} else
{
UE_LOG(LogTemp, Warning, TEXT("!!!SOMETHING IS WRONG IN YOUR JUMP CHECK!!!"));
}
}
}
Maybe you will use it, maybe not. But it’s not bad to have it.
Both of this examples are in the same project and the same .cpp file.
I know that this does not really answer your question, but I think it’s more of practice than of the wright way.
Two different programmers will have 2 different opinions on best practices.
I do not remember any rule that “forbids” or “recommends” using nested if’s or a bunch of if-return statements.
That is the beauty of programming: if a + b = 1 it does not really matter if
- a = sqrt(4) and b = -1 => sqrt(4) + (-1) = 2 + (-1) = 2 -1 = 1, OR
- a = 1 and b = 0 => 1 + 0 = 1
The end result is the same a + b = 1
But like [C0d3M0nk3y] said in an above post: “If I’d asked for a refactor to make it more maintainable and concise on a PR because of this and I got a load of if return statements instead the following conversation would be less than comfortable for the dev unless they were straight out of uni.”