Placing custom code in a System namespace - c#

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.

Related

Usage of extension methods for framework types

In a new line of work I have been told to avoid using Extension Methods for Types that you (or your organization) have no control over, meaning external libraries, framework types such as string, list, and others.
The argument I was given is that this will be bad if the framework developer now decides to implement a method that has the same names and/or parameters as your extension method.
While this problem may arise, this argument effectively reduces the usability of extension methods to nearly zero. Would this argument be considered valid? I am not suggesting to use extension methods everywhere, but I would like to know of similar arguments for and against it.
It's an argument which has some merit, but in lots of cases the problems can be avoided:
If you control your code and can easily update it if necessary, then you can easily write unit tests to detect the problem and correct it if it occurs. (I assume you'd be validating any update to the external library before deploying it anyway.)
If you trust the external library developer to follow normal good practices for backward compatibility, then they shouldn't be adding members to interfaces anyway, as that would break existing implementations... so you could at least write extension methods for interfaces.
If your extension methods have names which would be very unlikely to be added to the external libraries, then practically speaking it's not an issue. For example, if your company writes Frobulators, and that's a term which is specific to you, then writing
public static Frobulator ToFrobulator(this string Frobulator)
really isn't going to be a problem in reality.
Of course, the risk is there, but defining something on closed or sealed types you have no control over is exactly what extension methods is about. If you'd only create extension methods on types from your own, the effectiveness of extension methods (compared to regular methods) would be minimized.
There is a very easy 'solution' for this in naming conventions. If you'd prefix or postfix your extensions with a specific identifier, you will be sure Microsoft doesn't create a similar method.

Pitfalls of creating extensions to the .net System libraries inside the System namespace

At all the companies I have worked at I end up championing a core set of libraries that do nothing more than enhance and extend the .net libraries. Usually I have the namespaces such that they start with our company name but the sub namespaces mirror those of the System namespace.
Foo.IO;
Foo.Web
What I plan to do is take this one step further and replace the company namespace with the system namespace so that you only have to have the one using statement and thus have a better enhancement to the core library.
namespace System.IO
{
public static class StreamExtensions
{
...
}
}
The actual question
Now I know that this is possible, Microsoft do it in their own libraries and I have seen it done in other third party libraries but what I want to know is what, if any, are the long term implications of doing this such as a class name conflict in later versions of .net? Has anyone done this and had to handle a complication that has broken the simplicity of just being able to add an assembly reference?
UPDATE
Unfortunately this has turned into more of a debate of whether you should or should not do this which probably belongs over on Programmers. Indecently there is another SO question which does ask this but that was not the point of the question.
I wanted to know if there is a scenario that would crop up further down the road that would cause compilation errors or a strange behavior. The only two arguments that have come up is.
Microsoft adds a method to an object that matches the signature of extension method in the library but this is a mute point as it would make no difference to what namespace the extension method lives in as the implementation on the object would take precedence.
Someone else does the same thing in their third party library and we have a name clash. This is more likely and something we already have to deal with where third party libraries ILMerge other libraries into their assembly.
Just to be clear this is a stand alone library, it is for in house use, not to be made available externally and is there to extend the existing System libraries through Extension methods.
I would suggest do not do this. System namespace is .NET Framework namespace, if you want to customize classes from that namespace, make it explicit in your code.
That means make the customized class part of you custom namespace.
Do not mess up the things.
This may be a little off-topic, but in reference to the alternative approach you mention:
Usually I have the namespaces such that they start with our company name but the sub namespaces mirror those of the System namespace.
I've had some issues with that approach.
My company name is Resolv - as such, a lot of the stuff I write ends up going into a namespace in the form of Resolv.<ProjectName> (the rest will be <ClientName>.<ProjectName>).
I started building my library of extension methods, static classes and so-on in a namespace called Resolv.System
However, that created namespace resolution issues when using "fully qualified" type names that start with System (e.g. var myVar = new System.Collections.List<int>();).
While I would never use a fully qualified name in that particular case, it's something I do on occasion if the type I'm referencing is the only one from that namespace in the entire code file (in which case adding a using isn't warranted) - or on those occasions when two namespaces imported (with using statements) contain conflicting type names. Automated code generation tools (like resharper) often add those sort of references when there isn't an appropriate using statement too.
If I'm working on code within some namespace anywhere inside Resolv (e.g. Resolv.MyInternalProject) - and I put in what should be a fully qualified name - confusion ensues because of the Resolv.System namespace. The compiler walks back up the current namespace, gets to Resolv and then finds Resolv.System. That means - for example - that new System.Collections.List<int>() will attempt to use the non-existent class Resolv.System.Collections.List<int>().
Of course, I can get around that by using the form var myVar = new global::System.Collections.List<int>() but that's ugly and sort of a pain).
I've opted instead to include a "project name" in my extensions namespace tree, so now instead of Resolv.System I have Resolv.Extensions.System. From there the child namespaces mirror the System namespace (e.g. Resolv.Extensions.System.IO). That way I can have better control over whether I want to have System.xxx.xxxx references refer to my extensions, or the .net ones from any given code file (and it's only one using statement to add to my code files when I want to "turn on extensions").
Of course, I'll still have the System.xxx.xxx namespace confusion when working on code inside the Resolv.Extensions namespace - but that won't bug me on a daily basis! :)
What I plan to do is take this one step further and replace the
company namespace with the system namespace so that you only have to
have the one using statement and thus have a better enhancement to the
core library.
I don't understand how this will enchance the core library. What happens when Microsoft adds the same method to the String class and it does something entirely different? This is the reason they should be in their own namespace.
Now I know that this is possible, Microsoft do it in their own
libraries and I have seen it done in other third party libraries but
what I want to know is what, if any, are the long term implications of
doing this such as a class name conflict in later versions of .net?
The long term implications is if Microsoft adds the same method to a class as the extension method you create.
Has anyone done this and had to handle a complication that has broken
the simplicity of just being able to add an assembly reference?
I don't understand the reason you want to reduce the amount of references. You gain nothing by doing this, having utility methods in their own namespace and class is a valid design decision, people assume they will be seperate and not part of a Microsoft namespace.
It is a valid statement but the question about what are the
implications. Other people, including myself, have shied away from
doing this because of a "gut" feeling about messing with someone
else's namespace but no one has said do not do it because of this. If
you have a specific factual reason I would love to hear it.
The implication is a developers assumptions that the System namespace is filled with only Microsoft code.

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.

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

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.

Naming types in a namespace by the .NET Framework Design Guidelines

I'm having some problems to come up with a sane type naming scheme for our new line of applications. I want to follow the .NET Framework Developer's Guide - Design Guidelines for Developing Class Libraries, but I'm starting to wonder if that's such a good idea.
I'd like to use the Company.Product.Feature namespace scheme as a basis.
Problem 1: We have our own control and form base classes, and I want these to go into the Company.Product.Forms namespace. However, according to the guidelines, we shouldn't let our type names be Control or Form, even if they are in our own Company.Product.Forms namespace, since they will clash with system types.
Problem 2: We have some distinct feature areas in the application and I want these to go into their own Company.Product.Feature namespace. Lots of these features have similar design, with a controller and some views, so under each Company.Product.Feature namespace I'd like to have types named Controller, SomeView, AnotherView, etc. However, according to the guidelines, we shouldn't have the same type names in different namespaces.
The only solution I see to overcome these problems is to prefix the types with something that in some way makes the namespaces redundant. Or not?
Microsoft clearly favors some redundancy. A common example is:
System.Xml.XmlDocument
General class names, even bound within a proper named namespace can cause headaches for the many programmers who like to avoid fully qualifying their class instantiations. "Document" could be an Xml, Html or word document. This ambiguity will cause endless confusion if you happen to import more than one namespace with a "Document" class.
I'd prefer Company.Product.UI, for some reason. I would use that naming for the web, too.
Regarding problem 1, if these are base types, you might include Base in the class name.
Then, you typically have a set of domain specific controls, which won't clash with built-in types.
If you also keep wrappers for common UI controls(TextBox, DropDownList etc), then i would actually recommend use a prefix for them,
maybe this prefix is an abbreviated name of the product.
And then, if you do that, then you might want to be consistent, and do it for all types,
regardless of whether they are ambigious names or not.
I tell you from my own experience.
You'll end up constantly hovering over variables to see their full type names, etc, you will use aliasing etc..
The code will be harder to read.
Problem 2: While at GUI layer, i tend to break these rules, because you will want naming consistency(common verbs; Show,Edit,List). If the guideline tells you otherwise, i would believe it is because it is simply not specific enough.
First post here in StackOverFlow, on an old question. Please, be kind with me :)
General class names, even bound within a proper named namespace can cause headaches for the many programmers who like to avoid fully qualifying their class instantiations. "Document" could be an Xml, Html or word document. This ambiguity will cause endless confusion if you happen to import more than one namespace with a "Document" class.
Microsoft MIGHT sometimes favor some redundency but it's not always de case.
As for the Document vs XMLDocument problematic, when you know there might be more than one type of document, why not just include the qualifying part of the namespace in the declaration?
For example :
Xml.XmlDocument
vs
Html.HtmlDocument
Instead of importing the XML and HTML namespace, why not just include the containing namespace? It would become like this :
Xml.Document
vs
Html.Document
If it makes logical sense, then do it. They are just guidelines, not the LAW. (not that you cant break that too.)
Having classes in the with the same name in different namespaces is just is against the guidelines for a reason, it makes reading the code just a little bit harder because when you see "Controller" you have to mentally map it to "Feature1.Controller" or "Feature2.Controller".
I would prefer to use Company.Product.Features.Feature1.Feature1Conroller with the redundant information or maybe Company.Product.Features.Feature1Controller if it bothers you (and I personally don't like having too many namespaces).
But feel free to break the guidelines, rules are there to make you think before you break them :-)

Categories