Years ago I was talking to a friend who was just starting to learn about coding. He'd looked at some of my code, and asked why I used class properties with getters and setters instead of public fields. "Isn't it just more code for no real benefit?" he asked. And he was right; in every case, I had a getter and setter simply acting as a public interface to a private field.
I thought about his question for a second, not really knowing the answer. Frankly, it was just The Way I Learned To Do It. And to my dismay, he didn't just go away while I struggled to think of an answer. I eventually waved my hands dramatically and yelled "encapsulation!" Yes, that'll do nicely, I thought. Later that day I was thinking about it some more, and realized that in most cases, he was right. Still, getters and setters are great for inherited classes in which a method of calculation may be different. Accessors certainly have their place, but that place isn't necessarily everywhere.
If only I'd worked with Chris and crew; I hadn't even thought of something like this:
public partial class MyAspNetPage : Page
{
private string _searchparts = "";
protected string SearchParts
{
get { return _searchparts; }
set { _searchparts = value; }
}
protected string[] aSearchParts
{
get
{
if (SearchParts != null)
return SearchParts.Split(';');
else
{
Response.Redirect("Regulations.aspx");
return null;
}
}
// ...
}
}
Try doing that with a field! Chris has dubbed this the "when something is null, jump to a completely different page" design pattern.