I am using an ASP.NET MVC project and everytime I add a class to a folder it makes really long namespaces.
Example:
Project = Tully.Saps.Data
Folder = DataAccess/Interfaces
Namespace = Tully.Saps.Data.DataAccess.Interfaces
Folder = DataAccess/MbNetRepositories
Namespace = Tully.Saps.Data.DataAccess.MbNetRepositories
Question:
Is it best to leave the namespace alone and add the using clause to the classes that access it or change the namespace to Tully.Saps.Data for everything in this project?
Leave them alone and add the usings. You're asking for trouble manually changing things like that (harder to debug, inconsistent with other projects, et cetera).
It is really up to you how you want to deal with it. If you are only going to be accessing a member of a namespace once or twice, then adding the "using" statement really doesn't do much for you.
If you are going to use it multiple times then reducing the namespace chain is probably going to make things easier to read.
You could always change the namespace so it doesn't add the new folder name if you are just looking to logically group files together, without creating a new namespace.
According to FXCop, and I agree:
Avoid namespaces with few types
A namespace should generally have more than five types.
also (and this applies to the "single namespace" suggestion -- which is almost the same to say as no namespace)
Declare types in namespaces
A type should be defined inside a namespace to avoid duplication.
Namespaces
.Namespaces help us to define the "scope" of a set of entities in our object model or our application. This makes them a software design decision not a folder structure decision. For example, in an MVC application it would make good sense to have Model/View/Controller folders and related namespaces. So, while it is possible, in some cases, that the folder structure will match the namespace pattern we decide to use in our development, it is not required and may not be what we desire. Each namespace should be a case-by-case decision
using statements
To define using statements for a namespace is a seperate decision based on how often the object in that namespace will be referred to in code and should not in any way affect our namespace creation practice.
Leave it. It's one great example of how your IDE is dictating your coding style.
Just because the tool (Visual Studio) you are using has decided that each folder needs a new Namespace doesn't mean you do.
I personally tend to leave my "Data" projects as a single Namespace. If I have a subfolder called "Model" I don't want those files in the Something.Data.Model Namespace, I want them in Something.Data.
Related
I've inherited an old .NET 2.0 C# system in work, currently sifting my way through an enormous code base. As I am a graduate I'm interested in why the existing developers did certain things, certain ways. One particular habit the previous developers had was, instead of importing the references at the top of the class like so -
using System.IO;
They did this continually throughout - (rather than importing the reference at the top).
System.IO.File.Exists();
Could anyone shed some light what the difference(s) is/are other than having to type more code? The system I'm working on is a business object orientated system (CSLA), and with no prior experience to this methodology, could someone recommend a good way to approach learning a system which I've inherited. I appreciate you can't see the system I've got but a bit of insight from someone experienced would be appreciated.
Regards.
It's just a style choice. Some people like to use the full names to know that local type names won't conflict with system types.
using statements are just a way to help the compiler find the referenced types at compile time, there is no difference at runtime between;
using System.IO;
File.Exists();
and
System.IO.File.Exists();
Could anyone shed some light what the difference(s) is/are other than
having to type more code?
It's a coding standard / style choice as Joachim says.
I personally use usings for most namespaces but will use fully qualified names if it makes the code clearer in a particular case. Such as to avoid ambiguity.
Further, I've seen some teams use usings for .NET types and fully qualified names for types that they have developed or very specific scarse types that the team is not always aware of. Using fully qualified names states that this type is rare and this is the namespace it's in so you don't have to go looking for it.
Could someone recommend a good way to approach learning a system which
I've inherited
Don't try to understand everything up front. Learn what you need to know when you need to know it (when you are making changes). Gather a high level understanding about where things are so you can find them quickly when you need to work on them.
I usually prefer using statements but there are places where it will be ambigious to use it.
Consider the following
namespace MyNamespace
{
public class File
{
public static bool Exists()
{
return false;
}
}
}
Then use
using System.IO;
using MyNamespace;
File.Exist();//this is now ambigious
In such cases you've to use System.IO.File.Exist();
Or
using System.IO;
using MyFile = MyNamespace.File;
File.Exist();//this is call is not ambigious since File means System.IO.File only
Other than these I don't find any reason to use full name rather than using statements
Personally, I like using the full name if I'm only using something in that namespace once or twice in the class. This way, it doesn't clutter up IntelliSense, and it helps me focus on the namespaces I actually care about in that particular class.
I come from Java and see that package in Java is very convenient. When you move a class to another package, it will change automatically the package. (of course, by IDE such as Eclipse or Netbean)
But C# is using namespace and don't have my namespace renamed automatically like it does in Java. For example I have a file which namespace is com.app and I put it in com.app, but at later time, I move this file to com.lib folder and its namespace still be com.app. So, I find this is difficult to manage because I'm moving it manually.
Please give me help in how to fix my problem. (that namespace of file is named by folder it contains, and when I move to other, I will automatically change). Can we do it?
I fix the problem by using an IDE plugin called Resharper. (Among many, many useful features) it highlights when a namespace is wrong (based on the folder hierarchy and root namespace of the assembly) and can fix it for you.
Note that unlike in Java, there are sometimes very valid reasons for a class to be in a namespace other than the one inferred by the directory structure. A good example might be extension method classes, which need to be in scope in the class that is invoking them. Therefore it is common to have:
/myProject
/extensions
/MyExtensionMethodClass.cs
with a namespace like myProject (so that the extension methods can be used anywhere in myProject without a using directive)
Thats actually because C# has the concept of partial classes , that is , you can distribute your C# class along several files instead of just having it coded into a single file , like Java. For that reason , namespaces in .Net are distributed containers instead of centralized containers , defined by your namespace orperator.
I was wondering, what the purpose of Namespaces in C# and other programming languages is...
As far as I know, they are used for two things:
To structure the project into meaningful pieces
To distinguish classes with the same name
My Question is: Are there any other things to consider when using namespaces? Do they have an impact on performance or something like that?
As far as I know, they are used for two things:
• To structure the project into meaningful pieces
• To distinguish classes with the same name
That's basically it. I would add to your first point that namespaces provide structure larger than just that of the project, since namespaces may span projects and assemblies. I would add to your second point that the primary purpose of namespaces is to add structure to libraries so that it becomes easier to find stuff you need and avoid stuff you do not need. That is, namespaces are there as a convenience for the user of a library, not for the convenience of its creators.
A secondary purpose is to disambiguate name collisions. Name collisions are in practice quite rare. (If the primary purpose of namespaces was to disambiguate collisions then one imagines there would be a lot fewer namespaces in the base class libraries!)
Are there any other things to consider when using namespaces?
Yes. There are numerous aspects to correct usage of namespaces. For example:
violating standard naming conventions can cause confusion. In particular, do not name a class the same as its namespace! (See link below for details.)
using a namespace can bring extension methods into play that you didn't expect; be careful
where precisely the "using" directive goes can subtly change resolution rules in a world where there are name collisions; these situations are rare, but confusing when they arise
collisions often arise in contexts where machine-generated code is interacting with human-generated code; be careful in such situations, particularly if you are the one writing the code generator. Be very defensive; you don't know what crazy name collisions the person writing the human-generated half is going to create.
See my articles on this subject for more details:
http://blogs.msdn.com/b/ericlippert/archive/tags/namespaces/
And see also the Framework Design Guidelines for more thoughts on correct and incorrect conventions for namespace usage.
Do they have an impact on performance or something like that?
Almost never. Namespaces are a fiction of the C# language; the underlying type system does not have "namespaces". When you say
using System;
...
class MyException : Exception
...
there is no class named "Exception". The class name is "System.Exception" -- the name has a period in it. The CLR, reflection, and the C# language all conspire to make you believe that the class is named "Exception" and it is in the namespace "System", but really there is no such beast as a namespace once you get behind the scenes. It's just a convention that you can sometimes omit the "System." from the name "System.Exception".
According to MSDN a namespace has the following properties:
They organize large code projects.
They are delimited with the . operator.
The using directive means you do not need to specify the name of the namespace for every class.
The global namespace is the »root« namespace: global::System will always refer to the .NET Framework namespace System.
Secondly namespace has nothing to do with performance but if you have created your own namespace so you should follow the conventions across the project.
It doesn't affect performance. But for code readability, I would recommended remove unwanted using statements
Namespaces are a concept pulled from earlier technology, like XML. THe namespace gives context to your classes, allowing you to have say a CUstomer object in your domain and in your data code.
You can also use namespaces to alias, which still does the above, but allows shorter naming for the particular object.
domain.customer
versus
data.customer
You've touched upon the two main reasons. This is an old article from MSDN but it still applies: Namespace Naming Guidelines
In the Java world the naming practice is to reverse the domain name of the company who owns the product and include the product's name after that. So com.example.product might be a valid namespace, but you don't really see that in .NET so much.
Those are the big ones right there.
There aren't really performance benefits. At least, not directly. without namespaces framework would have to search the a lot more places to find the code you are trying to include - It would almost be like needing to load up the ENTIRE .NET framework for every project. Well, not really, but its close enough for this discussion.
In the past I've always gone and called my namespace for a particular project the same as the project (and principle class) e.g.:
namespace KeepAlive
{
public partial class KeepAlive : ServiceBase
{...
Then from other projects whenever i've called that class its always been:
KeepAlive.KeepAlive()...
I'm now beginning to think that this might not be such a good idea, but I'm sort of stumped what to actually call my namespace. What do other people do? Do you just have one namespace for all your projects?
We have this simple scheme:
CompanyName.ProductName
Then the application layer, e.g.
CompanyName.ProductName.Data
CompanyName.ProductName.Web
etc.
And inside divided per module and/or functionality, which normally correspond to folders
CompanyName.ProductName.Web.Shop
CompanyName.ProductName.Web.Newsletter
etc.
BTW: You can find answers to similar questions here:
.NET namespaces
Should the folders in a solution match the namespace?
Having the name of a class being the same as the namespace is a bad idea - it makes it quite tricky to refer to the right thing in some cases, in my opinion.
I usually call the project (and namespace) an appropriate name and then have "EntryPoint" or "Program" for the entry point where appropriate. In your example, I'd probably call the class "KeepAliveService".
CompanyName.ProductName.AreaOfSystem.SubAreaOfSystem
Never call them the same name as a class.
Our areas include things like:
Services
Smartcard
UI
Sub-areas are used sparingly but when relevant:
Smartcard.Mifare
Smartcard.DESFire
Ours don't correspond to folders because logically that may not be the case. To ease solution explorer navigation we might section off certain bits in folders but that doesn't necessarily mean the namespaces should follow the folder structure. Especially if there are only a few files in the folder (a namespace with few types is usually silly).
i name my namespaces with the common descriptor of all the things that go into that namespace.
I like the java package way: com.stackoverflow.Data (or whatwever the primary domain name of your company may be).
That way your namespaces won't be ambiguous.
we stick to the old
uk.co.company.system.layer
scheme that way we keep collisions down to a miniumum as we use a lot of MS Server products and it helps conceptual seperations.
eg.
uk.co.acme.biztalk.bizutils.
Should the folders in a solution match the namespace?
In one of my teams projects, we have a class library that has many sub-folders in the project.
Project Name and Namespace: MyCompany.Project.Section.
Within this project, there are several folders that match the namespace section:
Folder Vehicles has classes in the MyCompany.Project.Section.Vehicles namespace
Folder Clothing has classes in theMyCompany.Project.Section.Clothing namespace
etc.
Inside this same project, is another rogue folder
Folder BusinessObjects has classes in the MyCompany.Project.Section namespace
There are a few cases like this where folders are made for "organizational convenience".
My question is: What's the standard? In class libraries do the folders usually match the namespace structure or is it a mixed bag?
Also, note that if you use the built-in templates to add classes to a folder, it will by default be put in a namespace that reflects the folder hierarchy.
The classes will be easier to find and that alone should be reasons good enough.
The rules we follow are:
Project/assembly name is the same as the root namespace, except for the .dll ending
Only exception to the above rule is a project with a .Core ending, the .Core is stripped off
Folders equals namespaces
One type per file (class, struct, enum, delegate, etc.) makes it easy to find the right file
No.
I've tried both methods on small and large projects, both with single (me) and a team of developers.
I found the simplest and most productive route was to have a single namespace per project and all classes go into that namespace. You are then free to put the class files into whatever project folders you want. There is no messing about adding using statements at the top of files all the time as there is just a single namespace.
It is important to organize source files into folders and in my opinion that's all folders should be used for. Requiring that these folders also map to namespaces is unnecessary, creates more work, and I found was actually harmful to organization because the added burden encourages disorganization.
Take this FxCop warning for example:
CA1020: Avoid namespaces with few types
cause: A namespace other than the global namespace contains fewer than five types
https://msdn.microsoft.com/en-gb/library/ms182130.aspx
This warning encourages the dumping of new files into a generic Project.General folder, or even the project root until you have four similar classes to justify creating a new folder. Will that ever happen?
Finding Files
The accepted answer says "The classes will be easier to find and that alone should be reasons good enough."
I suspect the answer is referring to having multiple namespaces in a project which don't map to the folder structure, rather than what I am suggesting which is a project with a single namespace.
In any case while you can't determine which folder a class file is in from the namespace, you can find it by using Go To Definition or the search solution explorer box in Visual Studio. Also this isn't really a big issue in my opinion. I don't expend even 0.1% of my development time on the problem of finding files to justify optimizing it.
Name clashes
Sure creating multiple namespaces allows project to have two classes with the same name. But is that really a good thing? Is it perhaps easier to just disallow that from being possible? Allowing two classes with the same name creates a more complex situation where 90% of the time things work a certain way and then suddenly you find you have a special case. Say you have two Rectangle classes defined in separate namespaces:
class Project1.Image.Rectangle
class Project1.Window.Rectangle
It's possible to hit an issue that a source file needs to include both namespaces. Now you have to write out the full namespace everywhere in that file:
var rectangle = new Project1.Window.Rectangle();
Or mess about with some nasty using statement:
using Rectangle = Project1.Window.Rectangle;
With a single namespace in your project you are forced to come up with different, and I'd argue more descriptive, names like this:
class Project1.ImageRectangle
class Project1.WindowRectangle
And usage is the same everywhere, you don't have to deal with a special case when a file uses both types.
using statements
using Project1.General;
using Project1.Image;
using Project1.Window;
using Project1.Window.Controls;
using Project1.Shapes;
using Project1.Input;
using Project1.Data;
vs
using Project1;
The ease of not having to add namespaces all the time while writing code. It's not the time it takes really, it's the break in flow of having to do it and just filling up files with lots of using statements - for what? Is it worth it?
Changing project folder structure
If folders are mapped to namespaces then the project folder path is effectively hard-coded into each source file. This means any rename or move of a file or folder in the project requires actual file contents to change. Both the namespace declaration of files in that folder and using statements in a whole bunch of other files that reference classes in that folder. While the changes themselves are trivial with tooling, it usually results in a large commit consisting of many files whose classes haven't even changed.
With a single namespace in the project you can change project folder structure however you want without any source files themselves being modified.
Visual Studio automatically maps the namespace of a new file to the project folder it's created in
Unfortunate, but I find the hassle of correcting the namespace is less than the hassle of dealing with them. Also I've got into the habit of copy pasting an existing file rather than using Add->New.
Intellisense and Object Browser
The biggest benefit in my opinion of using multiple namespaces in large projects is having extra organization when viewing classes in any tooling that displays classes in a namespaces hierarchy. Even documentation. Obviously having just one namespace in the project results in all classes being displayed in a single list rather than broken into categories. However personally I've never been stumped or delayed because of a lack of this so I don't find it a big enough benefit to justify multiple namespaces.
Although if I were writing a large public class library then I would probably use multiple namespaces in the project so that the assembly looked neat in the tooling and documentation.
I think the standard, within .NET, is to try to do it when possible, but not to create unnecessarily deep structures just to adhere to it as a hard rule. None of my projects follow the namespace == structure rule 100% of the time, sometimes its just cleaner/better to break out from such rules.
In Java you don't have a choice. I'd call that a classic case of what works in theory vs what works in practice.
#lassevk: I agree with these rules, and have one more to add.
When I have nested classes, I still split them out, one per file. Like this:
// ----- Foo.cs
partial class Foo
{
// Foo implementation here
}
and
// ----- Foo.Bar.cs
partial class Foo
{
class Bar
{
// Foo.Bar implementation here
}
}
I'd say yes.
First, it will be easier to find the actual code files by following down the namespaces (say, when somebody e-mails you a naked exception call stack). If you let your folders go out of sync with namespaces, finding files in big codebases becomes getting tiring.
Second, VS will generate new classes you create in folders with the same namespace of its parent folder structure. If you decide to swim against this, it will be just one more plumbing job to do daily when adding new files.
Of course, this goes without saying that one should be conservative about how deep xis folder/namespace hierarchy goes.
Yes they should, only leads to confusion otherwise.
What's the standard?
There is no official standard but conventionally the folder-to-namespace mapping pattern is most widely used.
In class libraries do the folders usually match the namespace
structure or is it a mixed bag?
Yes, in most class libraries the folders match the namespace for organizational ease.