SSW Foursquare

Do you do your validation with Return?

Last updated by Brook Jeynes [SSW] 7 months ago.See history

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: 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: Good example - Using Return to exit early if invalid

We open source. Powered by GitHub