Software process and the ilk

Monday, July 31, 2006

C# Properties

The first time someone waved c# properties in my face, I smelled trouble. It reminded me of other silver bullets I've watched fly my direction, and I wondered what low-grade thought process crafted those gleaming orbs from marketing hype.

First, rough background. In java, you write:
public MyClass{
private int myValue;
public int getValue(){return myValue;}
public void setValue(int value){ myValue= value;}
}
In C#, with Properties, you write:
public MyClass{
private int myValue;
public int Value{
get{return myValue;}
set{myValue=value;}
}
}
One of the "big benefits" of Properties is that you can treat them like fields:
MyClass.Value = x;
But, when compiled, the properties get replaced with get_ and set_ methods. This is a Big Deal (tm) to me; it means Properties are lying. They're lying because you're calling a method, but you think you're calling a field. The overhead possibilities are terrible. You said
MyClass.Value;
thinking you're getting a fast value back, but that call could be running off to a database, worse, on another machine. You said
MyClass.Value+=x;
and you just hit that database twice. Convention says they shouldn't do that, but convention also says people shouldn't fly planes into buildings. Who are you going to trust?


This doesn't bother me nearly so much:
MyClass.getValue();
is telling me there may be some work involved. I'm more okay with it running to a database and coming back. I'm absolutely fine with it just returning a value. My expectation of a longish call was bettered by immediate response. It's like getting a Wendys Value Meal, and they give you a free ice cream. It makes you happy.

Properties do the opposite. I expect them to come back immediately; when they hit a database, it's like getting that Value Meal and having no bread on the sandwich. I'm kinda ticked, and I'm not going to go to that Wendys again.

So keep your Properties to yourself. I'm a happy man with my accessors and excessive parentheses and ice cream. Take your silver bullet and get the jerk who stole your bread.

No comments: