67

I'm working on an MVVM project, so I have folders in my project like Models, ViewModels, Windows, etc. Whenever I create a new class, Visual Studio automatically adds the folder name to the namespace designation instead of just keeping the project-level namespace. So, adding a new class to the ViewModels folder would result in the namespace, MyProject.ViewModels instead of just MyProject.

When I first encountered this, it annoyed me. My class names are pretty clear, sometimes even containing the name of the folder in them (e.g., ContactViewModel). I quickly found myself manually removing the folder name on the namespaces. I even tried at one point to create a custom class template (see this question), but I couldn't get that to work, so continued doing it manually.

I've begun to wonder, though, if this convention exists for a good reason that I'm just not seeing. I could see it being useful if you for some reason had lots of sets of identical class names organized into folders, but that doesn't seem like a particularly common scenario.

Questions:

  • Why is it common convention for namespace names to reflect folder structure?
  • Do you abide by this convention? Why?
Community
  • 1
  • 1
devuxer
  • 41,681
  • 47
  • 180
  • 292

10 Answers10

46

Same as you - I fought this for the longest time. Then I started considering why I created folders. I found myself starting to create folders to represent namespaces and packages instead of arbitrary buckets.

For instance, in an MVVM project, it might be helpful to put views and view models in a separate namespace. MVC will have a separate namespace for Models, Controllers, and Views. It is also beneficial to group classes by their feature.

Suddenly, the project feels more organized. It is easier for other developers to find where features are implemented.

If you standardize on your namespace practices, all of your projects will have the same predictable structure which will be a big win for maintenance.

Jordan Parmer
  • 36,042
  • 30
  • 97
  • 119
  • 1
    I believe folders should match namespace. You have to work with it though to make it useful. Actually, I'd personally like folders to be automatically created based on the namespace of your classes. – Didier A. Feb 18 '14 at 20:02
  • 12
    I believe in having root level child folders match namespaces, but sometimes I want to use folders to decrease the size of the solution explorer and use the same root namespace. E.g. say I'm working on a massive MVC Project and I have a bunch of pocos to represent all the data. So I have a folder called Entities, and giving all of them that namespace is cool. But I don't want to have 350 pocos in the root folder. I don't want to namespace all of them because I don't want to need 20 using statements to use a bunch of them in one file. All in Entities is good, all in the root folder is bad.. – Ryan Mann Sep 28 '14 at 04:00
  • I think it's worth pointing out that there is some strong critisism towards this sort of "package-by-layer" style, and many would argue that "package-by-feature" is preferable (e.g., instead of `Views/AccountView | Controllers/AccountController` you do `Account/AccountView | Account/AccountController`. the idea is to have a more modular architecture, and to avoid the issues of having a bajillion classes in Views and a bajillion gazillion classes in Models. I agree that folders should match namespaces though. why else are you even using folders? – sara Jul 16 '16 at 10:23
19

If you want some solid advice I'd recommend buying Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries which gives you all you need to know from the actual framework design team.

...the goal when naming namespaces is creating sufficient clarity for the programmer using the framework to immediately know what the content of the namespace is likely to be...

<Company>.(<Product>|<Technology>)[.<Feature>][.<Subnamespace>]

And importantly

Do not use the same name for a namespace and a type in that namespace

Fragmenting every 1/2 types into namespaces would not meet the first requirement as you would have a swamp of namespaces that would have to be qualified or used, if you followed the Visual Studio way. For example

Core - Domain - Users - Permissions - Accounts

Would you create

  • MyCompany.Core.Domain.Users
  • MyCompany.Core.Domain.Permissions
  • MyCompany.Core.Domain.Accounts

or just

  • MyCompany.Core.Domain

For Visual Studio's way it would be the former. Also if you use lowercase file/folder naming you're looking at renaming the class each time, as well as making one big namespace tangle.

Most of it is common sense and really down to how you would expect to see the namespaces organised if you were a consumer of your own API or framework.

Chris S
  • 64,770
  • 52
  • 221
  • 239
  • 3
    That book explicitly says that the file structure *should* match the namespace structure as much as possible. – Max Schmeling Aug 17 '09 at 18:27
  • 1
    As much as possible but I infer it to mean that 2 classes in a folder doesn't warrant a namespace, e.g. Helpers namespace, Extensions namespaces. – Chris S Aug 17 '09 at 20:44
  • If you look at MVC Source code http://aspnetwebstack.codeplex.com/SourceControl/latest#src/, you'll notice that they actually do stick to the folder namespace pattern. The Extension classes aren't in any subfolders. And any subfolders with one or more class have the subfolder in the namespace. Interesting. – harsimranb Aug 26 '14 at 22:46
  • 1
    Actually, if you look at the MVC source code, Microsoft explicitly does not follow this. In many folders, namespaces and folder structure match somewhat (though not rigidly). This is fine. But in other folders, namespaces are all over the place. And this is the correct way to use namespaces. Check out the folder src->Common. Namespaces change for almost every file. Rigidly matching namespaces to folders is bad practice and makes the framework designers' explicit choice to separate namespaces from folders worthless. – Ryan Horath Sep 07 '14 at 02:21
  • It seems like MVC's default folder structure leads people down the wrong path. `MyCompany.MyProject.Models`, `MyCompany.MyProject.Views`, and `MyCompany.MyProject.Controllers` starts to fall apart when you end up with a project that has 100s of views, controllers, and models. For example, I may have a master view that is made up of 20-40 partial views. Each partial view may have it's own view model. So now, I have 1 controller, that has up to 40 view models associated with it. The practice is to place all 40 of these view models into a single `Models` folder? Now imagine 10-20 views like this. – crush Mar 27 '15 at 13:43
  • I have been fighting Visual Studio's auto-refactoring functionality on this. I found that you can use the `editorconfig` file to state that you don't want the namespaces to be automatically updated to match the file structure by setting `dotnet_style_namespace_match_folder = false:none` under the `[*.{cs,vb}]` section. – JED Mar 18 '23 at 21:21
10

i was annoyed by this as well but working with and refactoring projects with large codebases quickly taught me otherwise. Having embraced the concept i think that it's a very good way to structure your code "physically" as well as logically. When you have a large project and the namespaces do not match up to the folders it becomes difficult to locate files quickly. It's also that much more difficult to remember where things are...

Also, if ReSharper recommends it, then it's probably a good idea. E.g. R# will complain if your class' namespace does not match its folder name.

Paul Sasik
  • 79,492
  • 20
  • 149
  • 189
  • 21
    Yes, but ReSharper also adds a "Namespace Provider" property to the property grid for a folder. If you set it to false, then the folder will no longer contribute to the namespace. This is good, for instance, for folders containing generated code. – John Saunders Aug 17 '09 at 18:31
  • Good call John. i never noticed that property. – Paul Sasik Aug 17 '09 at 18:37
  • @John: Thank you so much for this info! This is exactly what I was looking for when I found this thread. – Adrian Grigore Mar 31 '15 at 08:53
  • Any idea how this can be enforced without resharper? – David Sep 01 '16 at 08:24
6

File system folders and namespaces both represent a hierarchy. I seems perfectly natural to me to match the two. I go even one step further and use a 1:1 relationship between files and classes. I even do so when I program in other languages such as C++.

Now that you question the relation between these two hierarchies, I seriously wonder what you would like to represent by the file system hierarchy.

Malte Clasen
  • 5,637
  • 1
  • 23
  • 28
  • @Malte, I give an example of how I'm trying to divide up my code in the first para of my question (Model, ViewModels, Windows, etc.). But my classes typically have names like ContactWindow and ContactViewModel, so it's sort of obvious which class goes with which folder. That's why I was questioning the need for the hierarchical namespaces. – devuxer Aug 17 '09 at 18:17
  • I usually avoid duplicating names, so in this case I'd probably have a file ViewModels\Contact.cs containing the class ViewModels.Contact. There's nothing wrong using short class names if the namespaces are meaningful. And, by the way, using "var" avoids most of the text clutter often associated with namespace hierarchies. – Malte Clasen Aug 17 '09 at 19:00
  • @Malte, doesn't this mean you end up fulling qualifying a lot of class names, though? Not to say this is bad, but it does seem to add some burden. – devuxer Aug 17 '09 at 21:31
  • You can usually add using statements for the namespaces that are closely related, which eliminates most namespace qualifiers. Second, you can use .NET 3.5 "var" for variable assignments. Now you're left with a few function parameters and constructors. In my experience, this is a quite low number, if your code is well structured. If you often depend on a large amount of types in different namespaces, you might question your namespace layout or your class dependencies. It's a typical case for refactoring. – Malte Clasen Aug 17 '09 at 22:56
  • I generally agree about one class per file. One exception I like to use is if I have a specific collection class to contain only members of one class. I have these two in the same file, as they are very tight connected. – awe Aug 18 '09 at 10:00
6

While I agree with everyone else, that a physical structure matching the logical structure is helpful, I have to say I also fight with Visual Studio's auto-naming. There are half a dozen reasons why I have to rename classes:

  • I use a root "src" folder to visually separate my code from embedded resources
  • I want different capitalization
  • I'll organize my code into subfolders for organization within a namespace
  • I like to separate interfaces from implementations and base classes
  • I feel like it

With thiose reasons, I've resigned myself to having to adjust those for every class I create. My strategy to avoid the issue is copying a file that has the namespace declaration I want, and then immediately delete the contents.

Hounshell
  • 5,321
  • 4
  • 34
  • 51
5

One way of not following the convention is to create the file in the project root folder and then move it to the final sub-folder.

Anyhow, it is a convention I actually like. If I am splitting types into folders, then probably those types have some kind of conceptual grouping related to the folder. Therefore, it ends making some sense, their namespaces are also similar. Java takes this approach and enforces it with its package system. The biggest difference is that VS is only "suggesting" it to you, since neither the language or the CLR enforces it.

Rui Craveiro
  • 2,224
  • 16
  • 28
5

I think there are indeed valid reasons for having different structures for namespaces and project folders. If you are developing a library, the namespace structure should first and foremost serve the users of your API: it should be logical and easy to grasp. On the other hand, the folder structure should be primarily there to make life easy for you, the API designer. Some goals are indeed very similar, like that the structure should be logical, too. But there may also be different ones, e.g. that you can quickly select related files for tooling, or that it is easy to navigate. I myself for example tend to create new folders when a certain file threshold is reached, otherwise it just takes too long to locate the file I'm looking for. But respecting the designer's preference can also mean strictly following the namespace - if that is their preference.

So overall, in many cases it makes sense that both match, but I think there are valid cases to deviate.

What has been helpful in the past for me was creating a file (e.g. WPF UserControl) in one place to get the namespace right and then moving it to the "right" folder.

micTronic
  • 75
  • 1
  • 5
3

Before namespaces were introduced in C++ all C types were in the global namespace. Namespaces were created to segregate types into logical containers so it was clear what type is being referred to. This also applies to C#.

Assemblies are a deployment decision. If you look at the .Net framework a given assembly will contain multiple different namespaces.

Folder are to organize files on disk.

The three have nothing to do with each other, however, it's often convenient that the assembly name, namespace and folder names are the same. Note that Java collapses folders and namespaces to be the same thing (limiting the developer's freedom to organize files and namespaces).

Often we choose to organize files in a project into multiple folders because it's easier for me or my team to navigate the files. Usually this file organization has nothing to do with the namespace design we use. I wish the VS team would not default the namespace to be the same as the folder name or at least give the option back to not have this be the default.

Don't suffer, either change the template for new classes or correct the namespace after the new file gets created.

2

I also feel the pain with this 'by default' behaviour in Visual Studio.

Visual Studio also tries to set a namespace/directory match when you put your LinqToSql .dbml files in their own directory. Whenever I edit the .dbml, I have to remember to:

  • open the .dbml.designer.cs file
  • remove the directory/folder name from the namespace declaration

There's a way to stop this behaviour, though. It involves creating a custom class template.

Community
  • 1
  • 1
p.campbell
  • 98,673
  • 67
  • 256
  • 322
  • @pccampbell, the custom template didn't work for me. See the end of the 2nd paragraph of my question. – devuxer Aug 17 '09 at 18:09
  • 1
    IMO the worst part is that visual studio doesn't automatically refactor the name space if you move it to another folder. – FINDarkside Jul 06 '15 at 23:05
0

While I agree that matching the namespace hierarchy to the folder hierarchy is handy, and a good idea, I think the fact that Visual Studio doesn't seem to support switching this feature off is disgusting. Visual Studio has a lot of applications, and there are plenty of coding styles and ways of structuring the source file folders that are perfectly fine.

Let's say there's thousands of files that belong in a namespace, but the programmer just wants to group them into folders to make the hierarchy easier to navigate. Is this really such a bad idea? Will this really make things so un-maintainable that it should be forbidden by the IDE???

Let's say I'm using Visual Studio to work with Unity. Now, all my scripts are in the "Assets.Scripts" namespace. Not only is there a useless Assets namespace which contains no scripts now, but "Assets.Scripts" is meaningless - it does not describe what project or part of project the source file belongs to. Useless.

Sava B.
  • 1,007
  • 1
  • 10
  • 21