| hellswraith's profileCoding and BeerBlogLists | Help |
|
June 25 Guarding ClausesI have been reading Jimmy Nilsson's latest book titled "Applying Domain-Driven Design and Patterns With Examples in C# and .NET". In the refactoring section, he eluded to Guarding Clauses. He put a name to something that I have been doing in my own development without knowing that others have talked about it as a good practice.
To be fair, he mentioned that it originated from Martin Fowler in his refactoring book. Either way, it felt good to know that on my own I came up with something that others would consider best practice.
So, just what is a guarding clause? Well, it is where you guard your code without mixing all the code up in if statements. That is probably way overly simplistic, but below is a simple example to follow:
Here is a method before being refactored to use guarding clauses. Notice that the two if statements have nothing to do with what the method is supposed to do, they are just there to ensure the variables are correct before executing the code that needs to run. In affect, they are guarding the functionality in order for the code to run as expected.
When you look at that code though, it just looks messy. You could simplify it to this if you wanted to:
Still, just doesn't seem right that the functionality of the method is in-cased in a if statement. Using a guard clause, the method now looks like this:
The benefit to doing it this way is really shown when the method has many more lines of code, but for the example I didn't want to confuse the concept with what the code does. Further refactorings can make this code even clearer if you wanted to:
We just extracted out the conditional logic to a new method to provide better readability to our code.
Our team has been using these concepts on our current projects with great success. It is nice to glance at a method and realize that if conditions are not met, the code will not execute . It is easier that trying to execute the code in memory to see what code will run and when. Readability is key to this refactoring!
Brian Russell
Trackbacks (1)The trackback URL for this entry is: http://brianrussell.spaces.live.com/blog/cns!E1994C805737F3CB!199.trak Weblogs that reference this entry
|
|
|