tags:

views:

305

answers:

2

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?

+2  A: 

StyleCop (and I agree here) wants you to split this into multiple lines. It doesn't like if statements on one line, for (arguably) good reason - this causes an inconsistent usage pattern for if statements, which is one of the reasons that rule exists in the first place.

To get the behavior you're showing, you'd likely need to use the SDK to write your own customized rule for that specific case, and then disable the default rule.

Reed Copsey
+2  A: 

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.

Troy Hunt