开发者

What are the pros and cons of using accessors in C# [duplicate]

开发者 https://www.devze.com 2023-02-19 11:34 出处:网络
This question already has answers here: 开发者_开发技巧 Closed 11 years ago. Possible Duplicate: public variables vs private variables with accessors
This question already has answers here: 开发者_开发技巧 Closed 11 years ago.

Possible Duplicate:

public variables vs private variables with accessors

I am currently building a small application to manage an XML file. Each entry is represented in the code by an instance of a custom class. Now to set and get the properties, I can either allow direct access to them, or use accessors. Which one would be better, and why?


There're no pros and cons of using accessors or not: you must use them.

It's just an OOP principle: encapsulate the access to the class fields or calculated values so consumers of them won't care about how some value is retrieved or assigned.

Why? Because of encapsulation. It's one of most important principles of OOP, since this ensures the way a value is retrieved and assigned in a single point.


Pros:

  1. Encapsulation - can change implementation later on without recompiling everything that uses the DLL
  2. Can be put into interfaces (that cannot have fields)
  3. Can be overridden (made virtual)
  4. Many serializers will only serialize properties, not fields
  5. WPF binding only works on properties

Cons:

  1. More code to type (but really not much more with auto-implemented properties)

In general, I'd always use them on any significant class. At least I'll be using auto properties.


In this specific scenario, the obvious advantage of accessors is that you can limit access to only those properties and children that are valid for your XML schema (assuming that a schema exists, which should be so because you are in control of the XML). This will be implemented by the setters, but the getters will also help you reduce typing a bit.


Accessors let you in the future change how things work under the hood... maybe you change the XML schema or ditch XML altogether... you could modify the accessor implementation so that any code calling your class can remain as-is.

The only benefit of not using accessors is that you then have a few less lines of code to maintain.

Definitely use accessors for sharing things between classes.

0

精彩评论

暂无评论...
验证码 换一张
取 消