Why should I avoid using Properties in C#?

后端 未结 14 531
渐次进展
渐次进展 2020-12-22 18:05

In his excellent book, CLR Via C#, Jeffrey Richter said that he doesn\'t like properties, and recommends not to use them. He gave some reason, but I don\'t really understand

14条回答
  •  北海茫月
    2020-12-22 18:28

    Well, lets take his arguments one by one:

    A property may be read-only or write-only; field access is always readable and writable.

    This is a win for properties, since you have more fine-grained control of access.

    A property method may throw an exception; field access never throws an exception.

    While this is mostly true, you can very well call a method on a not initialized object field, and have an exception thrown.

    • A property cannot be passed as an out or ref parameter to a method; a field can.

    Fair.

    • A property method can take a long time to execute; field access always completes immediately.

    It can also take very little time.

    • If called multiple times in a row, a property method may return a different value each time; a field returns the same value each time.

    Not true. How do you know the field's value has not changed (possibly by another thread)?

    The System.DateTime class has a readonly Now property that returns the current date and time. Each time you query this property, it will return a different value. This is a mistake, and Microsoft wishes that they could fix the class by making Now a method instead of a property.

    If it is a mistake it's a minor one.

    • A property method may cause observable side effects; field access never does. In other words, a user of a type should be able to set various properties defined by a type in any order he or she chooses without noticing any different behavior in the type.

    Fair.

    • A property method may require additional memory or return a reference to something that is not actually part of the object's state, so modifying the returned object has no effect on the original object; querying a field always returns a reference to an object that is guaranteed to be part of the original object's state. Working with a property that returns a copy can be very confusing to developers, and this characteristic is frequently not documented.

    Most of the protestations could be said for Java's getters and setters too --and we had them for quite a while without such problems in practice.

    I think most of the problems could be solved by better syntax highlighting (i.e differentiating properties from fields) so the programmer knows what to expect.

提交回复
热议问题