when a property should be a method

§ September 29, 2009 13:46 by beefarino |

I posted a quip on twitter this evening:

note to devs: a boolean property that expects to be set to only a false or true value (and throws otherwise) should be a method instead.

Several people prodded me for more an explanation, so here it is.

Say you have a default feature, and you want to offer consumers of an object the ability to disable the feature.  One common practice is to use a boolean property, consumed like so:

// ...
thingWithFeature.DisableFeature = true;
// ... 

It's simple and makes sense.  However, I'm finding a lot of hardware SDKs are throwing exceptions when you try to set such a property to false, in this example indicating that you do not want to disable the feature (forgive the double negative).  In other words, the property is settable to one specific value.  E.g., the SDK implementation looks something like this:

// ...
public bool DisableFeature
{
    set
    {
            if( ! value )
            {
                throw new ArgumentException();
            }
            
            // ... disable the feature when the value is false
    }
}
// ...

As a consumer of this object, there is only one path I can take with the DisableFeature property that will result in a valid operation.  The property syntax goads the consumer into failure by offering up an illusion of functionality that does not exist.  As a developer, I have every reason to assume that a boolean property can be set to true OR false.  If one of those is not appropriate, then the property isn't a property, it's a method:

// ...
public bool DisableFeature()
{
    // ... disable the feature
}
// ...

As a method, the one valid path is captured unequivocally, and it's not possible for consumers to assume they can do more than they are allowed by the SDK.



 
beefycode | CodePaLULza Caption Contest Winner!

CodePaLULza Caption Contest Winner!

§ March 26, 2012 11:40 by beefarino |

imageWell, I left the caption contest up for a week, and as promised I’ve chosen a winner.  The choice was hard, not because y’all are terribly funny but because most of you chose to go the obvious route and focus on my hair or make some off-hand reference to illicit substances.  No offense, but after 25+ years of looking like a ragamuffin I’ve heard ‘em all.

And the winning caption <drumroll />:

"OK, on to your code review...Oleg and Dimitri here are about to gang audit your code."

The winning caption was supplied by Marc Lyon, who wanted me to link to the website for his employer.  Congrats Marc!

About

View all posts by beefarino →


blog comments powered by Disqus