Thursday, February 24, 2011

Ask Specific Questions....

You might think the two if statements below are the same thing...

But if myCollection conforms to an interface, which has both Count and IsEmpty properties declared, then use IsEmpty if you mean IsEmpty.

I'm not for a moment suggesting that Count==0 will not reliably determine that the collection is indeed empty. But what if the object that implements the interface is a linked list, which implements count by iterating over the nodes?

No-one would do that. Would they?

What if it was some form of virtual collection.... Count may be quite expensive. And all you care about are two cases Count == 0 and Count > 0.

It's an unlikely side effect.

But in general, if someone has gone to the trouble of giving you a specific function, use it. They may have had something in mind when they wrote it.

Your code will be, if anything slightly clearer, there's very little down side.

No comments:

Post a Comment