I don’t do it often, however I early exit a lot to prevent nested blocks:
// Normally
if(!isDead())
{
// Do all this code
}
// Exit early
if(IsDead()) return;
// Skip all this code
I do it quite often if I want to pretty much just get out of the method, so rather than having a bunch of conditional statements inside the method that check for true/false and execute one after another, I just switch the logic around and exit early.
Proper example (not Java but still, shows what I mean):
public override void MousePressed(InputHandler.MouseButton button, int x, int y)
{
// If there is no entity to place and no layer, exit early
if (toPlace == null || layer == null || placed) return;
// If the left button is not pressed, exit early
if(button != InputHandler.MouseButton.LEFT) return;
// Check if there is already something in the cell
if (layer.GetCellAt(xx, yy).GetOccupant<Entity>() != null) return;
// Place the object in the cell
layer.GetCellAt(xx, yy).SetOccupant(toPlace);
Sprite s;
if (toPlace.TryGetComponent(out s))
subject.Notify("placedEntity", s);
// It has been placed, prevent any further input
placed = true;
}
Kind of avoided braces right?
Looks a lot nicer than:
public override void MousePressed(InputHandler.MouseButton button, int x, int y)
{
if (toPlace != null && layer != null && !placed){
if(button == InputHandler.MouseButton.LEFT){
// Check if there is already something in the cell
if (layer.GetCellAt(xx, yy).GetOccupant<Entity>() == null){
// Place the object in the cell
layer.GetCellAt(xx, yy).SetOccupant(toPlace);
Sprite s;
// I avoid braces here as I know NOTHING else will ever be called here
if (toPlace.TryGetComponent(out s))
subject.Notify("placedEntity", s);
// It has been placed, prevent any further input
placed = true;
}
}
}
}