Home
Do you do your validation with Return?
  v2.0 Posted at 30/01/2020 10:16 AM by Liam Elliott

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 ​

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments: