Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CA1500 vs. SA1309 - Which one wins?

I'll prefix by saying that I understand that both Code Analysis and StyleCop are meant as guidelines, and many people chose to ignore these anyway. But having said that, I'd like to see what the general consensus is with regard to these two rules.

Rule CA1500 says don't make parameter names and private field names the same.

Rule SA1309, on the other hand, says don't prefix members with underscore or "m_".

This leaves us with little options for distinguishing private backing fields from their corresponding parameters. Take these examples.

SA1309 complains:

class SomeClass
{
    int _someField;

    public SomeClass(int someField)
    {
        this._someField = someField;
    }
}

CA1500 complains:

class SomeClass
{
    int someField;

    public SomeClass(int someField)
    {
        this.someField = someField;
    }
}

What options do I have? I don't want to make the private backing field PascalCase, because this is the (I believe fairly universal) convention for public fields/properties. And I don't want to rename one or the other, just for the sake of resolving ambiguity.

So I'm left with one of the above two, which would require me to suppress one of the SA/CA rules.

What do you guys typically do? And more importantly, what do the authors of these rules think you should do (as neither provide alternative solutions in their documentation)?

like image 623
Jerad Rose Avatar asked Jul 09 '10 18:07

Jerad Rose


3 Answers

We turn off SA1309. The reasoning behind it is fairly weak.

Our team feels that the well-accepted practice of private members starting with underscores far outweighs the idea that someone might use a different editor on the code, which never happens in our shop anyway. As to providing an "immediate differentiation", the underscore does that as well.

If you really have developers that still use "m_" though and you still need to check for that, you could write a quick rule for just that.

like image 93
womp Avatar answered Oct 17 '22 16:10

womp


Here is my usual solution:

class SomeClass
{
    int SomeField{get;set;}

    public SomeClass(int someField)
    {
        SomeField = someField;
    }
}
like image 32
µBio Avatar answered Oct 17 '22 14:10

µBio


Based on what I've seen from Microsoft themselves, I say CA1500 wins.

If you look at the BCL, most of the code prefixes local fields with an underscore.

like image 2
Justin Niessner Avatar answered Oct 17 '22 15:10

Justin Niessner