Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How often do you see abuse of C# shorthand getters/setters?

In C# you can create getter/setters in a simpler way than other languages:

public int FooBar { get; set; }

This creates an internal private variable which you can't address directly, with the external property 'FooBar' to access it directly.

My question is - how often do you see this abused? It seems like it has a high potential to violate encapsulation best-practices often. Don't get me wrong, I use it as appropriate, and partial variations of it for read-only write-only types of properties, but what are your unpleasant experiences with it from other authors in your code base?

Clarification: the intended definition of abuse would indeed be creating such a property when private variables are appropriate.

like image 861
dreadwail Avatar asked Jul 02 '09 09:07

dreadwail


People also ask

What type of abuse is the hardest to detect?

Emotional or psychological abuse Emotional abuse often coexists with other forms of abuse, and it is the most difficult to identify.

What is the most frequent type of abuse?

Neglect is the most common form of child abuse.

What do you notice in the cycle of abuse?

The cycle of abuse is made up of four stages. These stages include the building of tension, the abuse incident, the reconciliation, and a period of calm.


2 Answers

I've seen it abused (in my opinion). In particular, when the developer would normally write:

private readonly int foo;
public int Foo
{ 
    get 
    { 
        return foo;
    }
}

they'll sometimes write:

public int Foo { get; private set; }

Yes, it's shorter. Yes, from outside the class it has the same appearance - but I don't view these as the same thing, as the latter form allows the property to be set elsewhere in the same class. It also means that there's no warning if the property isn't set in the constructor, and the field isn't readonly for the CLR. These are subtle differences, but just going for the second form because it's simpler and ignoring the differences feels like abuse to me, even if it's minor.

Fortunately, this is now available as of C# 6:

// Foo can only be set in the constructor, which corresponds to a direct field set
public int Foo { get; }
like image 152
Jon Skeet Avatar answered Sep 23 '22 09:09

Jon Skeet


There is no "abuse" in simply not writing the field manually; and it is good to encourage all access via the property (not directly to the field) anyway!

The biggest problem I know of is with binary serialization, where it gets a bit tricky to change back to a regular field without making it version-incompatible - but then... use a different serializer ;-p

It would be nice if there was a "proper" readonly variant, and if you didn't need to use :this() ctor-chaining on structs, but.... meh!

like image 23
Marc Gravell Avatar answered Sep 22 '22 09:09

Marc Gravell