Abbreviator methods are a great addition to the features of code contracts. They allow us to create a single abbreviator method that contains often used or grouped code contracts. This means that we can simplify our code and make it more readable.
We will create two methods with the same code contract requirements. We will then simplify the methods under contract by implementing an abbreviator method to contain the code contracts.
using
statement to the top of your Recipes.cs
class file:using System.Diagnostics.Contracts;
public static int MethodOne(int value) { Contract.Requires(value > 0, "Parameter must be greater than zero"); Contract.Ensures(Contract.Result<int>() > 0, "Method result must be greater than zero"); return value - 1; } public static int MethodTwo(int value) { Contract.Requires(value > 0, "Parameter must be greater than zero"); Contract.Ensures(Contract.Result<int>() > 0, "Method result must be greater than zero"); return (value * 10) - 10; }
StandardMethodContract()
to your Recipes
class. This method's name can be anything you like, but the signature needs to match the methods it abbreviates. Inside this method, add the required code contracts defined earlier in MethodOne()
and MethodTwo()
:private static void StandardMethodContract(int value) { Contract.Requires(value > 0, "Parameter must be greater than zero"); Contract.Ensures(Contract.Result<int>() >= 1, "Method result must be greater than zero"); }
StandardMethodContract()
method to identify it as an abbreviator method:[ContractAbbreviator]
[ContractAbbreviator] private static void StandardMethodContract(int value) { Contract.Requires(value > 0, "Parameter must be greater than zero"); Contract.Ensures(Contract.Result<int>() >= 1, "Method result must be greater than zero"); }
MethodOne()
and MethodTwo()
by simply referencing the abbreviator method in place of the code contracts:public static int MethodOne(int value) { StandardMethodContract(value); return value - 1; } public static int MethodTwo(int value) { StandardMethodContract(value); return (value * 10) - 10; }
using
statement to the Program.cs
class to bring the static class into scope:using static Chapter8.Recipes;
try { MethodOne(0); MethodTwo(1); } catch (Exception ex) { WriteLine(ex.Message); } ReadLine();
MethodOne()
, but leave the call to MethodTwo()
as is. Run your console application again:try { MethodOne(200); MethodTwo(1); } catch (Exception ex) { WriteLine(ex.Message); } ReadLine();