Use system namespaces for class libraries: good or bad - c#

Is it a good idea to use "system namespaces" in my class libraries?
Sample:
namespace System.Web {
public static class RequestExtensions {
public static bool IsPost(this HttpRequest r) {
return string.Compare(r.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase) == 0;
}
}
}
The advantage: no need to include additional uses-clauses (especially for extension methods), so all becomes available straight after adding reference to the library.
The best sample is NUnitEx project (which uses NUnit's namespace).
Disadvantages: potential name conflicts.

I have to second everyone else who says its a BAD idea. Namespaces are an organizational tool, on many levels. Not only do they allow you to reuse identifiers for your own purposes without conflicting with other companies, they also allow different companies to isolate their product from your's or anyone else's. Putting code into the System namespace can be very confusing for the people who use your types.
Additionally, people know that anything in a System namespace is good, solid, tested, community vetted, thoroughly documented code that came from Microsoft. Thats a pretty important set of factors to live up to...by sticking your code in the same namespace, not only are you claiming your code is that good, but you have to live up to it.

The design guidelines talk about namespace naming:
The general format for a namespace name is as follows:
<Company>.(<Product>|<Technology>)[.<Feature>][.<Subnamespace>]
For example, Microsoft.WindowsMobile.DirectX.
Do prefix namespace names with a company name to prevent namespaces
from different companies from having the same name and prefix.
There is no scope for reusing System or Microsoft here.

Very very bad. It's confusing, and you should only do it if you absolutely have to (there are some cases when it's needed).
Only ever do it when it's 100% required, don't ever do it just for 'convenience'.

I think it is not good idea, because may be Microsoft will decide to create RequestExtensions class in the next versions of framework, It is always good practice to start namespace with your company name to prevent name conflicts

Using a System-based namespace can make it harder for someone to pick up your code and figure out what it's doing. For instance, if I pick up new C#, I often end up Googling things like "System.Web.xyz" when I don't know something.
In this case, I probably wouldn't know that "System.Web.RequestExtensions" wasn't a real member of the System.Web namespace, so I'd get stuck looking for a class that doesn't exist.
So basically, my view is that you need to document it really well or find another namespace.

Related

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.

Is this the good pratice to name the namespace according to the directory name

I have a directory structure to store the source files. Is this the good practice to
name the naming space according to the directory structure?
Like
Models\model.cs
Data\data.cs
One is defined in namespace Models
One is defined in namespace Data
Yes, that's the typical approach, and it's also one that's supported by tools such as ReSharper.
The difference between this and the Java approach is that you don't add directories all the way down from the top - just from the default namespace for the project. So for example, suppose we were creating Foo.Bar.Baz.Model and Foo.Bar.Baz.Data, the C# and java solutions might be:
C#:
Foo.Bar.Baz
Foo.Bar.Baz.csproj defining a project with default namespace of Foo.Bar.Baz
Model\
SomeModel.cs
Data\
SomeData.cs
Java:
src\
foo\
bar\
baz\
model\
SomeModel.java
data\
SomeData.java
yes is the usual practice, but you also put the project name before the directory name so you will have: myclasslibraryname.Models.Model and myclasslibraryname.Data.Data
Yes. It is a common practice in Java (at least, the source code I've looked at for big projects has almost always been structured this way). Not as common in C# from what I've seen, but there's nothing keeping you from doing it, and it helps you find the code a lot faster.
You'll probably want a deeper namespace hierarchy than just one level though. It is common to preface it with your organization or group name, the project name, the library/program name, then code architectural names (like Model, View, Data, etc). Whatever makes the most sense for whatever scope the source code of your project will live.
Generally I think it is a good practice. When you do it in such a manner, while going through the code, you can generally associate or easy to locate and get to know where your code file is coming from.
This is also a good practice in terms for maintaining the code. Some new user comes in, he can just see the namespace and identify where the code files are located or needs to be searched.
I don't know really if this is good or not.
But I name it like this.
I defined categories for the different modules.
Like this:
Company.Common
Company.Common.Web
Company.Windows
Company.Windows.Services
Common represent a directory. Inside it I created a solution with VS2010.
Inside the solution I create a project for each part and therefor the subdirectories for the project and if the project is complex, more sub dirs for the existing classes inside the dll.
There I have a good overview in all views (dir - view and project view - code view ).
This is a convenient convention for many projects, and one which some tools support or expect.
However, this isn't the full story. Although it's a good default, I don't think it should be regarded as inviolable best practice, because there are some circumstances which might motivate doing things another way. Additional factors to think about include:
Unnecessary namespace proliferation
and deeply nested namespace
hierarchies can be a pain for users
of your types. In a large library you
may want to start organising the
source code files into some folder
structure before you feel the need to
impose multiple namespaces on your
clients.
Related to this, namespace
hierarchies in .NET are supposed to
work such that dependencies between
types go from child namespace to
parent, not the other way around.
This isn't always the natural way to
organise source code into
folders/directories. For example, one
often sees people creating namespaces
such as MyNamespace.Foo.Common
containing utility types used both by
types in MyNamespace.Foo.Bar1 and
those in MyNamespace.Foo.Bar2. It
seems sensible to them at the source
code organisation level, but it
breaks the namespace dependency
convention.
Sometimes you may want to provide
additional functionality by adding
some types to a library namespace by
distributing a supplementary assembly
rather than releasing a completely
new version of the full library
assembly. It's likely to be more
convenient to keep source code files
for the respective assemblies
separate from each other in the
repository, rather than to store them
together just so as to keep all types
for the namespace in the same folder.
In short, I'd say follow the usual practice unless you have a good reason to do otherwise. But don't let it deter you, if you have a good reason to make use of the fact that Namespaces can provide a grouping of types completely orthogonal to their grouping into deployable assemblies and the source code which builds those.

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.

Naming Conventions and Namespaces

If I have objects on one layer with the same name as objects on another layer, is it best to change the object names with some prefix or have new namespace and refer to them with fully qualified names? For example:
namespace Project1.Data
Object Person;
namespace Project1.Model
Object Person;
Data.Person.Name=Person.Name;
OR
dbPerson.Name= Person.Name;
I'd use namespaces and namespace aliases, e.g:
Define your classes in appropriate namespaces:
namespace Project1.Data
{
public class Person {...}
}
namespace Project1.Model
{
public class Person {...}
}
And where you use the classes, either use fully qualified names or define an alias for the namespaces (especially usefule if the full namespace is long):
using data = Project1.Data;
using model = Project1.Model;
data.Person p1 = new data.Person();
model.Person p2 = new model.Person();
//...
p1.Name = p2.Name;
It depends on how often you're referring to the overloaded name.
If you use it several times in one file, then use the first way.
If you use it only once or twice, then write out the fully qualified name, so that other people won't have to go hunting around at the top of your file to figure out what object you're referring to.
It really depends on the frequency you're requesting each of them. Generally, I use the shortened version for the type I'm referring to most frequently, and use the longer name for the type which is less frequently used. I'd say eventually, if you end up having a lot of usages of both in the same file, that you should use namespace aliasing, but for me, that's a last resort only after the code has bloated to a point where it's hard to follow what's going on.
Had the same thought myself. I think chaging the name of the classes is a bad Idea. For instance I have a data access layer and a business layer. Both deal with users. So I have...
Project1.Business.User
Project1.DataAccess.User
trying to think of inventive new names for the classes is a waste of time and will probably mean odd names for classes with little meaning. Naming classes can be enough of a headache already.
I agree with McWafflestix "I use the shortened version for the type I'm referring to most frequently, and use the longer name for the type which is less frequently used".
It's simple. Listening to the .NET framework guidelines for once actually helps (although plenty of material in the book is just plain Elements of Java style Yet Again in Redmond Wonderland)..
You should avoid similar type names in cross or intra-project/library mixing namespaces ie. mixing across domains and models in generial ( even in C++ one that is extremellly strict and powerful, it also has an incarnation in compiler, resolution and enum-style compiler crashes and problems).
Therefore even fully qualifying all the time is no fool-proof (and btw aliases and 'using' are extremely limited and cause mild duplication at best, as well as prove C# weakness in generic programming etc ).
In my experience, Data domain types are a primary target for a more appropriate name, and thus for name refactoring which is:
a) cheap (as a process in rich ASTs but simple adt-s support like in C#, right-click in IDE and feel powerful according to type-challenged dynamic Ruby fans/backers )
[can also be read as: 4.0 dynamic features sheep will blame everyone but not think about namespaces or functional JS, C-with templates(not C-with-classes), or similar ]
b) communicates the semantics better ie. the intent (ie. plumbing + support to build your own processing )
c) usually of primitive but typed nature or message ( typed not OO; ie. OO-style critique as in aforementioned book which itself breaks straight out of intro lifts all 'Models' to reference land)
d) and 'aliasing' becomes a useful artifact in cross-domain usage (which is actually possible and quite 2020-like.. ie. value-type programming )
There really are no rules but beware that you will see mixing of namespaces in development when least expected.. which means only one thing for a managed-minded dev: confusion. Plus somewhat less serious, more compile-time and IntelliNonsense errors of course..
Tough problem in all languages, so it is your design/naming issue.. Even tool vendors can mess up for machines to parse.. say output of enhanced popular IDEs based on outdated browse information; then again, others do it real well for managed languages.
Not that I am against duplicating names, there are cases (they are tough but necessary) when mixing dual + interop + representation etc other models where same name makes it more readable; ie. where duplication is a necessity of dual-usage.. but that is lower level idioms that C# is not friendly or encouraging of (re: in favour of overhead).

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