Do you do your validation with Return?

Loading last updated info...

The return statement can be very useful when used for validation filtering.

Instead of a deep nested If, use Return to provide a short execution path for conditions which are invalid.

private void AssignRightToLeft()
{
  // Validate Right
  if (paraRight.SelectedIndex >= 0)
  {
    // Validate Left
    if (paraLeft.SelectedIndex >= 0)
    {
       string paraId = paraRight.SelectedValue.ToString();
       Paragraph para = new Paragraph();
       para.MoveRight(paraId);
       RefreshData();
    }
  }
}

❌ Figure: Figure: Bad example - Using nested if for validation

private void AssignRightToLeft()
{
  // Validate Right
  if (paraRight.SelectedIndex < 0)
  {
    return;
  }
  // Validate Left
  if (paraLeft.SelectedIndex < 0)
  {
    return;
  }
  string paraId = paraRight.SelectedValue.ToString();
  Paragraph para = new Paragraph();
  para.MoveRight(paraId);
  RefreshData();
}

✅ Figure: Figure: Good example - Using Return to exit early if invalid

Categories

Authors

Need help?

SSW Consulting has over 30 years of experience developing awesome software solutions.

We open source.Loving SSW Rules? Star us on GitHub. Star