Encapsulating Fields - A Reason To Do It

posted on 10/04/07 at 09:28:00 pm by Joel Ross

Last night, I posted a question, "Why do you encapsulate fields?" asking why you should bother encapsulating private fields. I couldn't think of any solid reason to do it, but this morning, Matt Blodgett, who now works with me at NuSoft Solutions, pointed me to a Jeff Atwood post questioning the same thing. Jeff initially says you shouldn't write useless code, but then later updates it with reasons it's not useless to encapsulate fields:

  • Reflection
  • Databinding
  • Changing from fields to properties is a breaking change.

He links to an Abhinaba Basu post explaining that if you create a class with public fields and distribute it, and then later change it to use properties, and re-distribute it, even though it's not exactly obvious that you're breaking the interface, you are - so all clients have to recompile against the updated DLL even though no code changes are involved.

The other two bullets are important too. If you have a mixture of public fields (because they have no "need" to be properties) and properties (because they do something else when getting or setting), reflection isn't as simple - and changing from a field to a property could break your reflection code. Also, you can only databind to properties - the same way a web service proxy doesn't propagate fields.

At least I have a reason why I do what I do now!

Categories: Development, C#