Introduction
It is easy to introduce deep nesting in the code. There are several techniques to reduce the deep nesting. One of these techniques is called "Return Early". By reducing the deep nesting, it allows us to follow the logic easily. We can also spot potential bugs without spending too much time. I revisited Return Early technique recently and it will be the main content of this post.
Deep nested validation
Let's consider a method that returns a particular string depending on the input. The ideal input string would be "cat", and there are five things we need to check.
- null or empty
- shorter than 7 letters
- contains "bad words"
- contains any digits
- is "cat"
We can implement the validation above one by one.
nested if statements
public string CheckInputString(string inputString)
{
string[] badWords = { "dog", "dogs" };
if (!String.IsNullOrEmpty(inputString))
{
if (inputString.Length < 7)
{
if (!badWords.Contains(inputString))
{
if (!inputString.Any(char.IsDigit))
{
if (inputString == "cat")
{
return "Meow";
}
return inputString;
}
return "the string contains numbers";
}
return "please dont use the bad words";
}
return "too long";
}
return "null or empty";
}
not nested if statements
We can remove all the nested if statements above by focusing on the best case senario. In this case, having the input string being "cat" would be the best case. The rest of the cases are considered "wrong". As soon as we encounter the "wrong" result, we return a value and exit the method.
As you see below, we can resolve the deep nesting by utilizing the return early technique.
public string CheckInputStringFixed(string inputString)
{
string[] badWords = { "dog", "dogs" };
if (String.IsNullOrEmpty(inputString))
{
return "null or empty";
}
if (inputString.Length >= 7)
{
return "too long";
}
if (badWords.Contains(inputString))
{
return "please dont use the bad words";
}
if (inputString.Any(char.IsDigit))
{
return "the string contains numbers";
}
if (inputString != "cat")
{
return inputString;
}
return "Meow";
}
This should look a lot clearer than the previous example.
Conclusion
I revisited return early technique where we get out of the method as soon as we encounter unwanted situation by returning a value right away. This technique can be applied in many situations and it greatly increased the visibility of the code.
Top comments (0)