Public Fields versus Automatic Properties

前端 未结 12 2084
梦谈多话
梦谈多话 2020-11-21 23:34

We\'re often told we should protect encapsulation by making getter and setter methods (properties in C#) for class fields, instead of exposing the fields to the outside worl

相关标签:
12条回答
  • 2020-11-22 00:03

    Changing from a field to a property breaks the contract (e.g. requires all referencing code to be recompiled). So when you have an interaction point with other classes - any public (and generally protected) member, you want to plan for future growth. Do so by always using properties.

    It's nothing to make it an auto-property today, and 3 months down the line realize you want to make it lazy-loaded, and put a null check in the getter. If you had used a field, this is a recompile change at best and impossible at worst, depending on who & what else relies on your assemblies.

    0 讨论(0)
  • 2020-11-22 00:04

    If you decide later to check that the title is unique, by comparing to a collection or a database, you can do that in the property without changing any code that depends on it.

    If you go with just a public attribute then you will have less flexibility.

    The extra flexibility without breaking the contract is what is most important to me about using properties, and, until I actually need the flexibility, auto-generation makes the most sense.

    0 讨论(0)
  • 2020-11-22 00:06

    In a related question I had some time ago, there was a link to a posting on Jeff's blog, explaining some differences.

    Properties vs. Public Variables

    • Reflection works differently on variables vs. properties, so if you rely on reflection, it's easier to use all properties.
    • You can't databind against a variable.
    • Changing a variable to a property is a breaking change. For example:

      TryGetTitle(out book.Title); // requires a variable
      
    0 讨论(0)
  • 2020-11-22 00:06

    One thing I find very useful as well as all the code and testing reasons is that if it is a property vs a field is that the Visual Studio IDE shows you the references for a property but not a field.

    0 讨论(0)
  • 2020-11-22 00:10

    There is nothing wrong in making a field public. But remember creating getter/setter with private fields is no encapsulation. IMO, If you do not care about other features of a Property, you might as well make it public.

    0 讨论(0)
  • 2020-11-22 00:11

    It's all about versioning and API stability. There is no difference, in version 1 - but later, if you decide you need to make this a property with some type of error checking in version 2, you don't have to change your API- no code changes, anywhere, other than the definition of the property.

    0 讨论(0)
提交回复
热议问题