The Daily Parker

Politics, Weather, Photography, and the Dog

Use property accessor methods, even inside your classes

Genius Boy here just spent ten minutes debugging a class because I used the private field directly inside the class, instead of the property accessor method.

Here's what the property looked like:

public string FileSpec
{
	get { return _fileSpec; }
}
private string _fileSpec;

Notice there's no set method. The file spec is set only in the constructor, and is immutable at runtime. That means that throughout the class I had code like this:

if (File.Exists(_fileSpec))
{
	_cache.Load(_fileSpec);
}

The problem? Well, the private data could contain any number of tokens representing disk or remote folders, which wasn't a requirement when the class was first built.

The solution? C# 2.0 gives you the power to create an accessors of different visibilities, like this:

public string FileSpec
{
	get { return _fileSpec; }
	private set
	{
		_fileSpec = DeTokenize(value);
	}
}

The constructor now looks like this:

public MyClass(string fileSpec)
{
	FileSpec = fileSpec;
}

And then the code that uses the value can do this:

if (File.Exists(FileSpec))
{
	_cache.Load(FileSpec);
}

All better.

Comments are closed