The code that validates your method’s inputs is called a Guard Clause. It makes your code more understandable and it protects you from bugs and unexpected behaviors.
For example, lets assume we have a simple method that validates a Url:
If we pass null as the url parameter then the method will return false. At first glance, this may seem ok, since null is indeed an invalid url. However this wasn’t our intention and we do not consider null a valid input value.
So we could rewrite the method as:
That if expression is a Guard Clause. However we can do better than that, since repeating this code over and over in all of our methods is a bad practice. (DRY principle).
So lets create a helper class:
And use it like this:
Note: I am usually against the usage of static methods. However in this case, I believe this a rare exception where a static method can be used since it is not affecting our code’s testability and it does not increase it’s complexity.
We can keep adding more Guard Clauses to our helper class as needed. Here are some more:
Note: Some may disagree with Guard Clauses like “IsLessThan” and “IsMoreThan” because they may step into business logic rules. It’s up to you to decide.