Best practices: C# Extension methods namespace and promoting extension methods - c#

I know there exists already a post, describing nearly the same, but I think mine is a bit different.
What I would like to know is how you organize your extension methods in terms of assigning the namespace. Currently - for the extension methods in our framework - I use the following namespace pattern
MyCompany.Web.Utils
and inside I have the extension method classes. This is fine for me with the disadvantage that the extenders are not immediately visible to our software developers. Consider the case where I have a StringExtender class which provides a quite handy extension method "In" that extends the String object. Having the extension method withing the above mentioned namespace, our programmers won't see the extension method unless they explicitly include its namespace. Instead, if I would put the extension method in the System namespace, everyone would immediately see it, but I've read that this is bad practice.
So my question is how you do promote your extension methods s.t. they are used by your developers.

We put them all in their own namespace Company.Common.Extensions. That way, if you have any of our extension methods, you have them all. Plus, at least at my shop, we don't have to worry about our developers not knowing about extension methods. I have the opposite worry, extension method overload! :)

The problem here is not the naming of the namespace, it's the lack of documentation and education of your developers.
Put them in whatever namespace makes sense, write a wiki article documenting all your extension methods, then send an email to your developers with a link to the wiki article.

This is not a namespace problem it is a communication problem.
If these methods are useful you need to communicate this to the developers and, conversely, act on the feedback from them (with appropriate levels of judgement).
Placing anything into the System namespace is a recipe for disaster and confusion later. The only times you ever want to do this is to 'back port' functionality into older frameworks and then you probably shouldn't do it yourself but should use something like LinqBridge to do it.
Be wary of the desire to throw all extensions into one namespace unless they really are widely useful together. Some developers may find the wood lost for the trees if they are bombarded with everything and the kitchen sink via intellisense.
Keeping the namespace the company name is sensible in general to avoid confusion.

#Juri- If you think about it this is the same problem as developers knowing that class X exists in the .NET framework. Communication is key that all team members use the right classes, be they extension methods or some other helper.
As JP has stated, I often see extension methods in some kind of subfolder called Extensions. Hopefully when you state you use my.company.web.utils the namespace is actually Pascal cased?
Even if you put them in a good place there is no 100% guarantee that other developers will use them.

Presuming you use Visual Studio, one way would be to create a custom Class template (or modify the default one) so that whenever a developer creates a new class file it automatically has a using statement with your namespace(s). See Customize Visual Studio 2005 Templates for Coding Productivity.

Yes,i think put the Extension methods in own company namespce is best practices. put it in System namespace is a lazy operation

I'm dumb, lazy and minimalistic, so I put them at the same namespace as the type they extend. In this way there is no need for extra using statements, documentation or emailing about them (Winston).

I like the way ReSharper solves this problem.
ReSharper discovers any available extension methods, even without the corresponding usings. In case the using is not present, Intellisense also shows the namespace where the extension resides, making clear where the extension comes from and indicating that selecting it will add the using. (Example below.)
Naturally, only namespaces reachable by the current project, i.e. directly or indirectly referenced, are included.
Here is an example of what Intellisense might show if there are two extension methods. The first one comes from a namespace that we have already included. The second comes from a namespace that we have not (yet) included.
AddMvc
AddEntityFrameworkSqlServer (Microsoft.Extensions.DependencyInjection)

We put everything into the same Namespace and Class, however we use partial classes to keep them organized.
For example:
ExtensionMethods-String.cs
ExtensionMethods-DataObject.cs
ExtensionMethods-Debug.cs
...etc all have partial classes...

You can achieve what you want by putting extension methods in the global namespace. That's what I do and they're then available without needing any using statements.

Related

Do extension methods benefit in any practical way from being a part of a static class vs. [theoretically] a part of a namespace?

When it comes to extension methods class names seem to do nothing, but provide a grouping which is what name-spaces do. As soon as I include the namespace I get all the extension methods in the namespace. So my question comes down to this: Is there some value I can get from the extension methods being in the static class?
I realize it is a compiler requirement for them to be put into a static class, but it seems like from an organizational perspective it would be reasonable for it to be legal to allow extension methods to be defined in name-spaces without classes surrounding them. Rephrasing the above question another way: Is there any practical benefit or help in some scenario I get as a developer from having extension methods attached to the class vs. attached to the namespace?
I'm basically just looking to gain some intuition, confirmation, or insight - I suspect it's may be that it was easiest to implement extension methods that way and wasn't worth the time to allow extension methods to exist on their own in name-spaces.
Perhaps you will find a satisfactory answer in Eric Lippert's blog post Why Doesn't C# Implement "Top Level" Methods? (in turn prompted by SO question Why C# is not allowing non-member functions like C++), whence (my emphasis):
I am asked "why doesn't C# implement feature X?" all the time. The
answer is always the same: because no one ever designed, specified,
implemented, tested, documented and shipped that feature. All six of
those things are necessary to make a feature happen. All of them cost
huge amounts of time, effort and money. Features are not cheap, and we
try very hard to make sure that we are only shipping those features
which give the best possible benefits to our users given our
constrained time, effort and money budgets.
I understand that such a general answer probably does not address the
specific question.
In this particular case, the clear user benefit was in the past not
large enough to justify the complications to the language which would
ensue. By restricting how different language entities nest inside each
other we (1) restrict legal programs to be in a common, easily
understood style, and (2) make it possible to define "identifier
lookup" rules which are comprehensible, specifiable, implementable,
testable and documentable.
By restricting method bodies to always be inside a struct or class, we make it easier to reason about the meaning of an unqualified
identifier used in an invocation context; such a thing is always an
invocable member of the current type (or a base type).
To me putting them in the class is all about grouping related functions inside a class. You may have a number of extension methods in the same namespace. If I wanted to write some extension methods for the DirectoryInfo and FileInfo classes I would create two classes in an IO namespace called DirectoryInfoExtensions and FileInfoExtensions.
You can still call the extension methods like you would any other static method. I dont know how the compiler works but perhaps the output assembly if compiled for .net 2 can still be used by legacy .net frameworks. It also means the existing reflection library can work and be used to run extension methods without any changes. Again I am no compiler expert but I think the "this" keyword in the context of an extension method is to allow for syntactical sugar that allows us to use the methods as though they belong to the object.
The .NET Framework requires that every method exist in a class which is within an assembly. A language could allow methods or fields to be declared without an explicitly-specified enclosing class, place all such methods in assembly Fnord into a class called Fnord_TopLevelDefault, and then search the Fnord_TopLevelDefault class of all assemblies when performing method lookup; the CLS specification would have to be extended for this feature to work smoothly for mixed-language projects, however. As with extension methods, such behavior could be CLS compliant if the CLS didn't acknowledge it, since code in a language which didn't use such a feature could use a "free-floating" method Foo in assembly Fnord by spelling it Fnord_TopLevelDefault.Foo, but that would be a bit ugly.
A more interesting question is the extent to which allowing an extension method Foo to be invoked from an arbitrary class without requiring a clearly visible reference to that class is less evil than would be allowing a non-extension static methods to be likewise invoked. I don't think Math.Sqrt(x) is really more readable than Sqrt; even if one didn't want to import Math everywhere, being able to do so at least locally could in some cases improve code legibility considerably.
They can reference other static class members internally.
You should not only consider the consumer side aspect, but also the code maintenance aspect.
Even though intellisense doesn't distinguish with respect to the owner class, the information is still there through tool tips and whatever productivity tools you have added to your IDE. This can easily be used to provide some context for the method in what otherwise would be a flat (and sometimes very long) list.
Consumer wise, bottom line, I do not think it matters much.

(Question on best practice) Why is "using System.Text" there by default?

Every time I creat a class, I see using System.Text that is added (amongst other using) by default. Every time I remove it after a while because it is unused according to ReSharper.
Am I missing a best practice? Do you use that namespace often? In which situation?
There has to be a reason why this namespace is referenced by default.
Thanks!
The System.Text namespace contains classes, abstract base classes and helper classes.
Say for example if you wanted to take advantage of the StringBuilder, Decoder, Encoder, etc....
The classes above, plays a significant role in most cases in .net. But it is not necessary for it to be there in your code. It only applies as to when you needed it. The important thing is to know when you will need the namespace.
It is added in visual studio by default for the convenience of the developers. Same with the
System.Linq namespace, not all of the time you will be using it but for your convenience it is already added assuming that you would be using it and that would be up to you to remove it which is by case to case basis.
Sometimes it would be a lot easier to delete it if it is not needed than to figure out the namespace and type when you need it :)
More info regarding System.Text
If it's not being used, it shouldn't be in the code. If Visual Studio adds them by default, chalk that up to Microsoft just trying to make things easy for a developer, as it thinks those are very common namespaces, but depending on what you are doing they likely aren't needed in many classes, just as you experience.
If you don't like it you can always create your own item templates. See http://msdn.microsoft.com/en-us/library/tsyyf0yh(v=VS.80).aspx
You should add using only for those namespaces that you really reference in the code.
This way the source file will not have a huge 'using header' and fewer namespace conflicts.
As you are using Resharper it is very easy to follow this rule.
If you are not using it, don't include the namespace. It is just automatically included because it is one of the more commonly used namespaces. I generally use it if I want to use regular expressions or string manipulation methods. But if you remove it and there are no compiler errors, it is safe to leave it out.

Class library reference problem

I am building a class library and using its default namespace as "System". There suppose I am creating a generic data structure say PriorityQueue and putting it under System.Collections.Generic namespace.
Now when I am referencing that library from another project, I can't see PriorityQueue under "System.Collections.Generic" namespace anymore. Though the library is referenced I can not access any of the classes in it.
Can anyone shed some light on it please. I know that if I change the namespace everything will be ok, but I want to create a seamless integration like .net framework itself with other project, so that one can refer the library and forget about its namespaces.
This is a very bad idea. Pretend you didn't think it up, and use a real namespace.
One does not have "seamless integration" with the .NET Framework, either. If we want to access the List<T> class, then we have to write
using System.Collections.Generic;
If you put your class in MyCompany.Collections.Generic, then you'll get exactly the same level of "seamlessness" that is achieved by the .NET Framework itself.
If you are using the System namespace for your classes, then they will be found in System.
If you want them to be found in System.Collections.Generic, then you need to place them there.
But let's be clear, placing classes in System.* is a bad idea.
Putting stuff in system namespaces is a bad idea. Firstly it's better to know explicitly where the stuff your using is. However more importantly, if Microsoft releases new stuff that causes a naming conflict with yours, your stuff breaks.
The second reason is probably why you cant see your code.
Just create your own namespace, e.g. Anindya.Collections.Generic, as placing classes in predefined framework namespaces isn't a good idea. MS might introduce a same class in a later framework, leading to problems.
Did somebody mention yet that this is a bad idea? There are few reasons you wouldn't be able to see the class. Short from the assembly reference, there is only one good one: you forgot to declare the class public.
In case it wasn't clear: This is a REALLY bad idea.
The System name space should be considered reserved and verboten. If Microsoft decides to introduce a class in a framework update that conflicts with your System.mycrap.blah identifier in the future, you're going to have some pretty hefty refactoring on your hands, and, in the case of an app that's deployed to a client, an emergency update and potential liability for system downtime.
You wouldn't create your own class called "String." By the same token (pun), don't use reserved namespaces.
Also, the namespace "System" doesn't really describe the contents of your namespace. Typically, namespaces should mean something - like, BlogEngine, DatabaseCore, etc. Slapping everything into System is a lot like naming all of your variables "x," or "temp," and implies that the creator doesn't really understand the point of this level of code delineation and organization.

Placing custom code in a System namespace

Are there any best-practices that state custom code shouldn't be placed in a System namespace? Should System and its children be reserved for Microsoft code?
I ask because I'm writing a class library that will be used across many projects and I'd like to keep things consistent by placing it in System.InteropServices (since it deals with P/Invoke).
It's not a good idea because it defeats one of the primary benefits of namespaces: preventing name clashes. What if a newer version of the framework introduced an identically named type in that namespace?
This is particularly bad for System namespaces since they are imported in many other pieces of code with using directives and introducing custom types in those namespaces pollutes the naming scope of other source files with unexpected identifiers.
To categorize your custom interop related types, you can create a new namespace like MyProduct.InteropServices.
If you place a new class in System.InteropServices, every file that has a using System.InteropServices; clause is forced to have your class in scope, which may confuse the programmer. Since the programmer cannot defend oneself against this, I'd consider this bad practise.
I disagree with everyone.
I think that in a limited subset of cases (mostly with extension methods) it is perfectly reasonable to place code in a system namespace.
Here is my side of the argument from an email thread we had debating Extension methods in the System namespace over at EPS:
Ok, so here's my side of the argument:
I really like to minimize code. That includes usings.
Yes, ReSharper picks up extension methods and adds the usings for you but some people don't have ReSharper, and besides, I prefer Coderush which as of yet does not actually (as far as I know) pick up extension namespaces.
There are at least two different types of extension methods; ones that are helper methods for our application - including domain and application-specific helpers, and ones that encapsulate features and syntax that we believe the language should have had to begin with.
A good example of the latter is the ability to do "a {0} {1}".Format("b", "c") or someListOfStrings.Join(", ") rather than having to do String.Join(someStringList.ToArray(), ", "). Other more debatable examples are IEnumerable<T>.ForEach and the IsNull() extension to take the place of the clumsy object.ReferenceEquals(null, someVar) syntax.
My argument is, that there is every reason to place this latter classification - your team broadly agrees should be in the language but aren't - in the appropriate namespace (System, System.IO, System.Linq, etc.). We want those functions to be available everywhere, just like we prefer the foreach and yield keywords to always be visible. If it is application-specific however it should go in its own namespace. 90% of the time application-specific helper extensions should likely not be extensions and not even be static. I exclude from this statement using extension methods to provide aliases for function names.
You can get in some trouble with this of course when calling into assemblies that contain system-wide extensions. Suppose that I was referencing the assembly containing my void IEnumerable<T>.ForEach method and wanted to create my own ruby-like R IEnumerable<T, R>.ForEach (which is actually just a Select, but nevermind that). This would be a problem! What I like to do to mitigate the issue is to define my extension classes as being internal so that they can be used only on my project. This solves the problem nicely.

How do you manage the namespaces of your extension methods?

Do you use a global, catchall namespace for all of your extension methods, or do you put the extension methods in the same namespace as the class(es) they extend?
Or do you use some other method, like an application or library-specific namespace?
I ask because I have a need to extend System.Security.Principal.IIdentity, and putting the extension method in the System.Security.Principal namespace seems to make sense, but I've never seen it done this way.
Put your extensions in the same namespace as the classes they extend. That way, when you use the class, the extensions are available to you.
If you are writing a extension for Uri, put the extension in System.
If it's a extension for DataSet, put it in System.Data.
Also, Microsoft says this about extension methods:
In general, we recommend that you
implement extension methods sparingly
and only when you have to. Whenever
possible, client code that must extend
an existing type should do so by
creating a new type derived from the
existing type.
For more info about extension methods, see the MSDN page about extension methods.
If they're extension methods used throughout the solution (e.g. over 60% of classes), I put them in the base namespace of the solution (since they'll be automatically imported being in a parent namespace, no importing the common stuff every time).
In this category, things like:
.IsNullOrEmpty(this string value) and .HasValue(this string value)
However, if they're very specific and rarely used, I put them in a BaseNamepace.Extensions namespace so they must be manually imported and don't show in intellisense cluttering things up everywhere.
I would recommend putting all your extension methods in a single namespace (incidentally this is also what Microsoft did with Linq by putting them in a single class 'Extensions' inside the 'System.Linq' namespace).
Since Visual Studio provides no clues as to how to locate an extension method that you want to use, it reduces confusion by only having to remember one namespace.
I upvoted the answer from user276695 which seemed the simplest solution. However I found an even better solution: no namespace at all. You can put a static class with extension methods at the very root of a file, without wrapping any namespace declaration around it. Then the extension methods will be available without having to import/using any namespace.†
I'm slightly worried about being down-voted from namespace nazis. But I feel compelled to champion a slightly unorthodox position. At least in my line of work (IT) I find that most of my custom tools are easier to maintain without namespaces, and placing everything in one giant anonymous namespace. I'm sure there are other programming universes where this would not work as well. But perferences & circumstances being different, I just wanted to point out that you can in fact declare classes without namespaces, even classes with extension methods - for those who also find a giant anonymous namespace better.
† You also get to save one level of indentation. :-) And even with 3 giant monitors I'm always looking for ways to save screen real-estate.
My practice is to put the extensions in a namespace that is different from yet clearly identifies the source namespace that I'm extending.
Generally, I create a namespace by prefixing my "company name" part of the namespace path in front of the namespace I'm extending, and then suffix it with ".Extensions"
For example, if I'm extending (for no good reason) ::System.Text.StringBuilder because it's sealed, then I will put my extensions in the namespace ::CodeCharm.System.Text.Extensions.
That's a rule of thumb for when I make extensions that I suspect I could re-use those extensions in other solutions.
If you put them in a higher namespace than your current, they will be visible automatically.
So if you have namespaces for projects like:
AdventureWorksInc.Web
AdventureWorksInc.Logic
AdventureWorksInc.DataAccess
Then declare your extension directly in:
namespace AdventureWorksInc
{
public static class HtmlHelpers
{
public static string AutoCloseHtmlTags(this string html)
{
//...
}
}
}
This extension method will show up whenever you are writing code in any sub name space of AdventureWorksInc without the need for a using statement.
However, the above extension demonstrates a possible downside. Due to the fact that it operates on strings, it will now show up as an extension method for all strings, including those that aren't really HTML. This is actually not an issue with namespace scoping, but simply a misuse of an extension method. This should be a regular static that requires a standard parameter so the call is explicit.
Generally well designed extension methods with appropriately typed parameters will not show up on types that it would never apply.

Categories