Monday, November 5, 2007

Remove Unneeded Property

If you have a property that looks like the following just remove it. It is not adding any value.

public string PositionTitle
{
get
{
return this.positionTitle;
}
set
{
this.positionTitle = value;
}
}

Refactoring tools such as Resharper make encapsulating a field simple. So you can always refactor to the property later if you find that you need it.



Now doesn't the following code look so much nicer?

public string positionTitle;

5 comments:

Chris Barrow said...

If you're just accessing the field in this context only, then yes I can see the benefit. Although something in my head keeps telling me that accessing underlying data directly on a object is bad.

Nick Markovic said...

I would agree with you that accessing the underlying data would be bad in the last century before we had refactoring support. But now we have tools that make it easy to encapsulate as we need.

Nick Markovic said...

I would just like to add that If the property was inside a framework it would probably be best to leave it the way it is. In this case the added flexiblity that the property would give you would be paying for itself.

Greg said...

The reason to leave it as a property is that when its a property you can change the implementation and keep *binary* compatibility. I can always change a field to a property but it requires everything that references it to be recompiled. If its a property to begin with I can change it at will to a different implementation without need for recompile.

Admittedly most projects don't need this as they are small and always deploy all assemblies....

Englestone said...

By doing this you are making the Public Property a Public Field.

Just remember that in some cases you cannot bind to Public fields only Public Properties.

See.
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2192428&SiteID=1

-- Lee