Colin Bacon, web developer.

Enforcing naming conventions of async methods with NDepend

Enforcing naming conventions of async methods with NDepend

By convention, the name of an async method should end with the "Async" suffix. It's one of those things that can easily be forgotten by a developer and missed in a code review. By creating a custom rule, NDepend can report when this rule is violated.

Use tools with rules

NDepend comes with a set of queries and rules that can report the health and quality of your code base. You can also add your own using CQLinq (Code Query LINQ). Here's how to add a rule to report when an asynchronous method is not suffixed with "Async".

The steps

From the Visual Studio toolbar select NDepend > Rule > New... > ...Code Query

How to create a new rule from the toolbar

This opens a new query editor. For those not familiar with the CQLinq syntax visit the NDepend docs. The following query returns all methods declared with an async modifier whose name does not end with "Async".

JustMyCode.Methods.Where(m => m.IsAsync && !m.SimpleNameLike(@"Async$"))

To turn this into a rule prefix it with warnif count

warnif count > 0 JustMyCode.Methods.Where(m => m.IsAsync && !m.SimpleNameLike(@"Async$"))

Name the rule

// <Name>Async method names should be suffixed with 'Async'</Name>
warnif count > 0 JustMyCode.Methods.Where(m => m.IsAsync && !m.SimpleNameLike(@"Async$"))

Select Critical from the editor tool bar and then save.

Set rule to critical

That's it, you're done. Your rule will now appear in the Queries and Rules Explorer.