The trouble with properties

Properties are supposed to provide encapsulation for your getter and setter logic, but they really don’t enforce it. Here’s what I mean:

private String _title;
 
public String Title
{
    get
    {
        // do custom getter stuff here
        return _title;
    }
    set
    {
        // do custom setter stuff here
        _title = value;
    }
}

The private field _title is the backing store for the property Title. The issue is that I don’t want to manually create this backing store, and I really don’t want it to be available anywhere in the class. I want to force anyone who edits this class to modify the value using the property, not the backing store. You don’t have to create a backing store with a default property like this:

public String Title { get; set; }

This is convenient, but it beats the point entirely. I specifically want to avoid the backing store when I have custom logic in either the getter or the setter. Currently in C# and VB (and every other language I can think of for that matter) there is no way to force the use of the property internally. I think it would be ideal to have an automatic backing store that is only accessible within the getter and setter.

Am I crazy?

2 Comments

  1. J says:

    Couldn’t you create a Title class. put the string in there.
    then in your class; add the Title as an object instead of as a regular string.
    So, even people editing your class would have to use Title’s functions to modify it.

    more overhead; but it would fully encapsulate; unless someone alters the Title class.

Leave a Reply