Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting StyleCop rule SA1503 CurlyBracketsMustNotBeOmitted to be more flexible

Tags:

stylecop

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?

like image 867
Richard Ev Avatar asked Jun 09 '09 17:06

Richard Ev


2 Answers

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.

like image 73
Troy Hunt Avatar answered Sep 25 '22 15:09

Troy Hunt


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.

like image 39
Reed Copsey Avatar answered Sep 22 '22 15:09

Reed Copsey