Understanding guard clauses
A guard clause represents a condition the code must meet before executing a method. Essentially, it’s a type of code that “guards” against continuing the execution of the method if certain conditions aren’t met.
In most cases, guard clauses are implemented at the beginning of a method to throw an exception early when the conditions necessary for the method’s execution are not satisfied. Throwing an exception allows callers to catch the error without the need to implement a more complex communication mechanism.
We already stated that we use constructor injection to inject the required dependencies reliably. However, nothing fully guarantees us that the dependencies are not null
. Ensuring a dependency is not null
is one of the most common guard clauses, which is trivial to implement. For example, we could check for nulls in the controller by replacing the following:
_locationService = locationService;
With...