简体   繁体   中英

Namespaces in C#

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM