Thursday, April 09, 2009

Dear Java and C++ Coders,

You don't need getters and setters in C#. Check out properties. Or just type "prop" into Visual Studio and it will autocomplete the C# property structure for you.

Enjoy.

2 comments:

Anonymous said...

I think there are a few caveats to recommending properties, given cases where using them over get/set pairs may be undesirable:

1) When the operations may be expensive, such as a network or disk operation.
2) When there is a high likelihood that the get operation returns a different value than the one you just set.
3) When setting the same value multiple times has side effects.
4) When the get/set operation may frequently fail, especially for circumstances beyond the client's control.

Basically, properties are good when they act similarly to a straight field. It's not so good to have a property that reads a bitmap off disk when evaluated. (I believe you had something to do with that one. :)

Trimbo said...

I think these caveats apply to getters and setters in general, not just C# properties.

Sure, it's easier to have someone fall into the trap of calling an expensive get or set when properties are being used, since it's not always clear there's a method hiding back there. But in languages where getters and setters are standard practice (C++/Java), why is this any different? IIRC (I'm no Java guy), Java Beans require using getters and setters. If that's the case, then hiding of expensive operations within these is pretty much the same.

In the end the caveats you mention require documentation no matter what language is being used with data hiding constructs. BTW, I can't recall writing a getter that reads a bitmap off disk, but I've done so many stupid things over the years it wouldn't surprise me.