WiseTechGlobal / WTG.Analyzers

Analyzers from WiseTech Global to enforce our styles, behaviours, and prevent common mistakes.
Other
16 stars 3 forks source link

Analyzer to warn against a private setter on an effectively readonly property #87

Open bretehlert opened 5 years ago

bretehlert commented 5 years ago

I still see this kind of code from experienced developers sometimes:

class MyClass
{
    public MyClass(string something)
    {
        Something = something;
    }

    public string Something { get; private set; }
}

I guess they are not aware of the read-only auto-properties that were introduced in C# 6. The property Something does not need the private set and removing the private set is better as it demonstrates the immutability of the property and potentially the class.

Add a rule to warn against the private set when the only call to the property setter is in the class constructor.

brian-reichle commented 5 years ago

If the class uses code contracts and there happens to be an invariant on Something, then this is necessary as contracts gets confused by read-only auto properties.

Having said that, it's probably a good rule for the projects lucky enough to have dropped code contracts.

yaakov-h commented 5 years ago

This sounds like something another Analyzer should have taken care of already, though I can't find a corresponding FxCopAnalyzers rule or Roslyn-inbuilt rule.

Resharper has one, but we don't use that in the build (and I try to avoid it in general): https://www.jetbrains.com/help/resharper/AutoPropertyCanBeMadeGetOnly.Local.html

brian-reichle commented 4 years ago

I don't think this is realistically achievable with current Api exposed to analyzers.

https://github.com/dotnet/roslyn/issues/3394