Why Do You Encapsulate Fields?

posted on 10/03/07 at 10:28:33 pm by Joel Ross

I was having a conversation with a colleague today about some of the new features in Orcas, and he asked an interesting question. "Why is it a good practice to encapsulate fields?" I was a little taken off guard - I know I should do it, but I'm not sure why - yes, if you have to do something on the get or set of a property (like mark an entity as dirty), then you need it, but a lot of times, your property is just a wrapper around a private field.

From a consumer's perspective, what is the difference between this:

public string CustomerName;

and this:

private string _customerName;
public string CustomerName
get { return _customerName; }
set { _customerName = value; }

Realistically, if you're using a class with either of these approaches, you can't tell the difference. And I know what your first reaction is: "What if I need a real getter and setter later on?" That's a valid concern, but YAGNI comes to mind, as well as pointing out that changing from the first option to the second option is a simple, simple process - and can be even easier with a refactoring tool.

Now, in Orcas, it's much easier to use the second method over the first, because you can just do this:

public string CustomerName { get; set; }

But it's the same question. In the above case, it's even more obvious that the private field encapsulation isn't really necessary - you don't even know about it. I know one of the advantages of using Properties is that you hide internal data storage, and that's fine - except here, we're not doing anything special to store it, and it's not hard to convert to properties later on. Oh yeah - there's the web service proxy generation in .NET too, but that's not really a reason - if you accept that fields are OK, that's a bug in the proxy generator.

So, why do you encapsulate simple fields? What does it give you that you'd be missing by using the field? Of course, I'm asking this question not because I'm advocating not using properties, but because I didn't have a good answer when asked why I do it!

Categories: Development, C#