Software Design Blog

Journey of Rinat Abdullin

Better C# Design Contracts in Lokad Shared Libraries

Extensive codebase is one of the best testers.

I’ve just finished updating Enforce statements from the Lokad Shared Libraries with the new syntax that is based on retrieval of parameter name from .NET lambda with IL parsing. A couple of usability and stability issues were discovered and fixed wile pushing changes to the existing code-bases leveraging Lokad Shared.

And so there is the updated new syntax for declaring design contracts for arguments. Basically we just replace variable with the lambda and drop the duplicate name entry:

// null or empty check for strings
Enforce.ArgumentNotEmpty(companyName, "companyName");
// new syntax
Enforce.ArgumentNotEmpty(() => companyName);

// null check and rule check
Enforce.Argument(newName, "newName", ChecksFor.NewName);
// new syntax
Enforce.Argument(() => newName, ChecksFor.NewName);

// null checks for the collection and rule check for items
Enforce.Argument(messages, "messages", RulesFor.Message);
// new syntax
Enforce.Argument(() => messages, RulesFor.Message);

Additionally, There’s a nice improvement in lowering code duplication. This code block:

Enforce.Argument(controller, "controller");
Enforce.Argument(viewManager, "viewManager");
Enforce.Argument(workspace, "workSpace");

can be replaced by a single line:

Enforce.Arguments(() => controller, () => viewManager,() => workspace);

Obviously, variable name and its type will be retrieved and included into the exception, should any of the checks fail.

New package of Lokad Shared Libraries has been released (direct link).