Hey there. Me again. That annoying overexcitable programmer. An I sill LOVE Extension methods.
For the past couple of months I’ve experimented with a convention of placing the static class which declares an extension method in the same namespace as the extended type. I didn’t like having to look for extension methods when I wanted to use them (and even Resharpers “Add using” was less than perfect with extension methods). The fact is – if you have an extension – you need to be able to access it with ease. And what’s easier than always having it in Intellisense, just like any other method?
I’ve bounced this idea off my Israel Alt.Net peers, and Amir has noted that this is not future-proof, because someone could add a similarly-named method to the type, and on the next re-compile – invocations will go to it. If the methods would have been declared at another NS – at least I would have gotten a “redundant Using statement” warning from Resharper, and try to find out why.
1) What’s the deal with this lenient compiler? Why is this legal? Throw some compilation errors my way!
2) He’s right.
So I’ve come up with a naming standard that all extension methods will end with an X: the classic “string.IsNullOrEmpty(stringInstance)” will be “stringInstance.IsNullOrEmptyX()”.
This will solve the possible future naming conflict, allow me to declare extension methods in the same NS, and still wouldn’t really bother me when typing the methods name (since it is just a suffix).
I said I will try it out for a while and then decide.
A while passed and I like it.
The reflex-comment about “Hungarian notations are evil” bounces right off me. I think in this case – the fact that I know that some method is an extension does actually help me. Reading code (without an accessible F12 key) could be confusing if you see a method that “you don’t remember ever seeing before on that type”.
One exception to the rule could be extension methods for System.Object. I would not add those extension methods under System, because then they would affect everything. Even if you wrote a perfectly useful method (I had fun with a myObj.GetPrivateField<T>(“_MyField”) method once) – this would cause too much clutter for everyone else. This is the sort of method I would keep in the standard “YourProject.Infra.Extensions” namespace.
An exception to that exception is, of course, if you have a limited scope to begin with – this would not clutter anything: say you have (borrowed from SpecUnit) and assertion method like “myObj.ShouldNotBeNull()” – you could still declare it under System (in your tests project), because it will only be seen in the tests project, where it’s logical to have it everywhere.