What are the guard methods / classes?

I just noticed the defensive method / class mentioned in this question and I don't really understand the concept from the answers. And alas, Jon Skeet's link to the MS site never loaded. Several quick Google searches seemed to return only products, not software development concepts.

Any explanation and / or samples would be appreciated. (Especially with the .Net side of things.)

+2


source to share


3 answers


Safeguard clauses are part of aspect-oriented programming where you can define what is valid method input.

From what I know about the .Net implementation (which I haven't really looked at) you do it with attributes, for example.

public static void NeverGetNull([ThisParamNotNull]MyClass i, [ThisParamNotNull]OtherClass j)
{
   // Will never need to check for null values on i or j!
}

      



I do know which guard expressions Erlang owns, where method dispatch depends on guard methods. I'll give a little psuedocode below to illustrate the point:

myMethod(input i) where i is an int
{
 return i + 10
}
myMethod(input i) where i is an int and i > 10
{
 return i - 10
}

var i = myMethod(1) // returns 11
var i = myMethod(i) // returns 1

      

As it may not be obvious, you could provide a guard expression that is evaluated at submission time. Pretty neat, hey?

+1


source


If you don't specify an exception then .NET will generate RaiseContractFailedEvent

, but you can specify ArgumentOutOfRangeException

or ArgumentNullException

.

If you look at Jon Skeet's link you will see many examples in the pdf documentation:



Contract.Requires( x ! = null );

      

This is the part of the Contract where you specify the preconditions and postconditions. The advantage is that you don't have to do a lot of checking before using the input parameters, and this helps the calling function know that the result will be contractually compliant, so if the return string is not allowed to be null then you don't have to check for null when calling the function due to precondition checking.

+1


source


This is a pretty good summary of what a typical shell example looks like:

Refactoring protection clauses or "How to ask politely"

0


source







All Articles