When should I write a property?

From the blog “Fabulous adventures in coding“:

One of the questions I’m asked frequently regarding design of C# classes is “should this be a property or a method?” Here are my guidelines:

It was one of those articles [link to article] lingering in an unread Codeproject newsletter I hadn’t gotten around to reading (shame on me) and was about to delete whilst tidying my inbox but one of those rare blog entries I read in its entirety – Including comments.

This delay in reading was in fact a Good Thing as the huge comments that followed what is a good article were equally good – a rare thing indeed. I can relate to most of the comments as having started out 10 years ago not necessarily following the rules guidelines I’ve seen the repercussions myself.

Oddly though, the one new idea that I picked out as bleedin’ obvious and then kicked myself for not actually giving much thought to in the past was a little naming convention; having decided something is a method not a property, don’t just stick “Get” in front of what would have been the property name but name it so as to imply how expensive it is to call and implications:

  • GetValue() – A low overhead call
  • LoadValue() – Something that involves reading (particularly I/O- orientated operations such as file I/O) so expect it to be slower and liable to fail (exceptions galore).
  • GenerateValue() or CalculateValue() or BuildValue() or .. well can think of a few more, but the point is it implies that the function has to do some work so the caller may well want to cache the returned value.

OK, we already consider naming functions to describe what they are doing (and if you don’t, your fired!) but its that extra twist of including a hint as to the repercussions of the function that made me think.

Examples ? OK, a DirectShow library, I create a function to get the latest image, GetCurrentImage(). But behind the scenes this might be reading data back from the video render, quite a slow operation. Maybe ExtractLatestImage() would help convey this to the caller?

But then again, when I’m using intellisense to to find out what’s available on an object I often head for where the intellisense list starts with “get…”.

I’m beginning to ramble now – that’s why this is in the “Ramblings” category. But to summarise, consider giving a hint as to a function’s overhead when thinking up a function name.

All of which has nothing to do with the original prompt for this article.

 

Leave a Reply