Do you do your validation with Return?

Updated by Brady Stroud [SSW] 1 year ago. See history

123
<introEmbed body={<> 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

Acknowledgements

Adam Cogan
Related rules

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