Reputation: 737
I really don't like to call String.IsNullOrEmpty(str). That makes me need to think "String" class first, then call it on the object "str".
I like to call str.IsNullOrEmpty(), which doesn't need me to think "String" class.
The problem is that extension method accept null instance to call on, which is not the usual case when you call a normal method.
My question what do you think will be a convetion name for extension methods that accept null?
For string, that is easy, "IsNullOrEmpty()" (anything that contains "IsNull") sounds good for me.
For others, like GetDisplayName(), do we name it as "NullOrGetDisplayName" ?
Upvotes: 0
Views: 174
Reputation: 12372
I just don't understand your way of thinking here. Writing something like nullObject.IsNullOrWhatever() simply doesn't make any sense. You may or may not like the static form, but your solution feels really wrong to me.
Upvotes: 1
Reputation: 55062
Firstly, your thinking is wrong and you should adjust it. It is not correct to think of calling a method on a null object; indeed that's the very reason why you want to see if it is null!
Secondly, a method implies that it accepts null in the parameters it has. I don't think a naming convention is appropriate here. You may be able to eliminate null from your classes via, say, Spec#.
Upvotes: 2
Reputation: 57892
I'd go for mystring.IsNullOrEmpty()
for methods that can query "null" objects - it is obviously checking if the string is null, and as long as you are consistent with your naming throughout your codebase, nobody will have any trouble understanding/learning what it means.
For methods that apply something to an object and ignore null objects, I'd use "Safe", as in SafeGetDisplayName()
- this is a common and long-used standard (c.f. GetSafeHandle() in MFC)
Upvotes: 1
Reputation: 700152
The Nullable
class has a method named GetValueOrDefault
. The same form may be usable for some extension methods: GetDisplayNameOrDefault
or perhaps more specific GetDisplayNameOrNull
or GetDisplayNameOrEmpty
.
Upvotes: 0
Reputation: 3206
How about NullSafeGetDisplayName
or GetDisplayNameNullSafe
, indicating that's it's safe to call even when the object it's being called on is null
?
Upvotes: 1