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:
- Encapsulation - can change implementation later on without recompiling everything that uses the DLL
- Can be put into interfaces (that cannot have fields)
- Can be overridden (made virtual)
- Many serializers will only serialize properties, not fields
- WPF binding only works on properties
Cons:
- 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.
精彩评论