Search code examples
stylecop

Getting StyleCop rule SA1503 CurlyBracketsMustNotBeOmitted to be more flexible


I am having a hard time with StyleCop rule SA1503 (CurlyBracketsMustNotBeOmitted).

In my code I quite often have a pattern thus:

public void SomeFunction(string someArg)
{
    if (string.IsNullOrEmpty(someArg)) throw new ArgumentNullException("someArg");

    // rest of the function here
}

The rationale behind this is to save vertical space when doing multiple validation checks on a single argument and/or checks on many arguments. The logic in such a check is typically simple and concise and likewise for the exception that gets thrown.

However, I would never write

if (someConditional)
    DoSomeStuff();

I would always write

if (someConditional)
{
    DoSomeStuff();
}

So in summary:

  • Use curly brackets if the if statement is split across multiple lines
  • Don't use curly brackets for simple argument validation etc that can be easily (and readably) put on one line

Can StyleCop help me here?


Solution

  • As already mentioned, unfortuntely StyleCop rules are either on or off and can't be customised. It would be nice to have a simple way of customising rules but unfortunately you'll need to write them from scratch.

    The way I've used StyleCop is to focus on using as many of the built in rules as possible and where I really have a fundamental issue with a rule (code documentation, for example), I just turn it off. I'm not concerned enough about the exceptions to go to the extent of writing custom rules.