We are currently reorganising some of our services projects so their naming is more logical. We have the following structure:
Djp.Services.Type. ServiceName
This seems to make sense as a logical grouping, however what I want to know is, is it acceptable to have further levels under this based on the folders in the project. For example one project is called
Djp.Services.Management.Data
Under this project we have a "POCO" folder and a "Repositories" folder, which means, in principal, objects under these folders will have a namespace 5 levels deep.
Is this depth of namespace something that should avoided, or is it perfectly reasonable?
Any namespace that follows the logic of your application structure is fine - regardless of the length.
We have a namespace seven layers deep, with an eighth symbol on the end for the class. The dropdown in the top-left of Visual Studio 2010 that allows you to choose the class within this file doesn't fit our fully qualified class name, and when you mouse over it, there's no tooltip, so the only way to find the class name is to undock the source view and stretch it across two monitors.
I know this is dependent on the total length of the names, and not necessarily the number of nested namespaces, but I'm going to go ahead and define this as "too deep" :)
It can be handy to make your folder structure match your namespace structure, but it makes no sense to make a namespace structure match a folder structure.
The types and members of the namespace(s) are the things you are making. That is the output of your craft and the thing you should be concerned about. The files in the folder are a way to help you do so. You may have already structured the folders such that they match a sensible namespace (essentially you "wrote" the namespace structure when you did so), in which case all and good, but you may also have not done so. The namespaces will matter both to the creators of the assembly(s) and the users of it, the folder structure only to the creators.
Ignore depth, ignore folders, look at the spaces created by the names.
It something smells too long, step back and analyze it. If it passed muster, then I agree completely with #Bozho.
Software development is extremely objective and full of exceptions to hard-fast rules. (couldn't resist)
Tough to answer objectively, but there are a couple things that have given me pause in the past...
Serialization. When serializing classes, the fully qualified class names often go into some identifier that's included in the serialization. $type in a json file for example. Or on a message bus (e.g. NServiceBus) where they're used with various APIs. For example, I had a FQN of a class that was needed as an even type and the azure service bus API rejected it because it was too long.
Documentation. Pretty easy to explain this one - run docfx or some other document generator and then look at your table of contents. Have fun with that. Even when using swashbuckle to autogenerate your Swagger/OAS spec files -- you have some FAT object ids.
In code, when you have two classes with the same name from two different namespaces, they have to be qualified in the code. For example, you could have a bunch that look like this:
Dictionary<MyCompany.Application.Domain.Service.Models.SomeClass, MyCompany.Application.Domain.Service.Models.SomeOtherClass> _someLookup = new Dictionary<MyCompany.Application.Domain.Service.Models.SomeClass, MyCompany.Application.Domain.Service.Models.SomeOtherClass>();
^ that is all one field and it's not even close to the worst I've seen. You can alias them in the directives section to shorten them up in the actual code, but either way, you're gonna have some fat declarations.
I don't know that there's any "wrong" number of levels to go in the naming convention, but there certainly are implications. I'm starting to back away from the approach and something else. For example, I have the Solution named after what it is and have the projects short
MySolution
Project1
Project2
Etc
It's fairly rare that I run into naming collisions this way, and nine times out of ten, when I run into those situations, it's indicative of a different problem; code-smell really. That's just me. I've also tried to stop nesting directories so deep because those generally become implicit namespaces. You can have namespaces not match the directory structure but that's generally considered bad practice and get really confusing. I've been making my structures flatter and flatter with every new project.
Philosophically, what I would say is to NOT use namespaces as an organization device but rather as a scoping device. The primary difference being that we're engineers and we can organize and re-organize everything under the sun and argue about it all day long, but scoping is more objective. That is, I don't introduce a new scope until I know I need one; when I know I have a collision and renaming the contesting classes is worse that applying scope. "Getting ahead of the problem" in this context can get really messy. Over-engineering?
Related
The question might sound weird but it just came into my mind while I was creating a new project.
In Visual Studio, I can create a namespaces hierarchy as below as nested folders or I could just create individual folders with dot such as CompanyName.Common and CompanyName.Common.Util
Which one makes more sense in long run and for big projects? or would it make any better than the other?
Second question is is there any limitation in terms of how deep it can go or is there any performance affect of having 7-8 nested namespaces?
Your namespace names and your project folder structure are two separate things.
They just seem related because Visual Studio creates a default namespace name for you, each time you create a new folder and start creating classes inside it, based on the name of the folder and what other folders it's nested inside of.
However, you can rename those namespaces to anything you want. For example, the first class you create in "CompanyName.Common" will be given the namespace "TestPro.CompanyName.Common", but you can rename that to "MyNewNameSpace" if you want.
Which one makes more sense in long run and for big projects? or would it make any better than the other?
In the end, your folder structure is just a matter of whatever makes the most sense to you, and helps you keep things organized. If you like seeing everything at once, flattened out, then use the folders with dots in them. Personally, I prefer nesting folders, but it's really up to you.
Is there any limitation in terms of how deep it can go or is there any performance affect of having 7-8 nested namespaces?
Personally, I haven't had a reason to nest more than 3 or 4 folders deep. Either way you choose, you're more likely to hit a windows limitation of 260 characters before running into problems in Visual Studio performance (unless you're naming your folders with single letters or something unusual):
In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters.
Indeed, it's not that hard to hit (my folder names are ridiculous here, but I'm making a point ;) )
In my experience, every industrial project I worked on had a clear nested folder hierarchy. It seems like Microsoft also recommends nested folders from the links I've quickly looked at.
Example : http://msdn.microsoft.com/en-us/library/bb668954.aspx
Is it possible to create a namespace hierarchy in C++ that resembles how it works in C#. For instance if I were to need a type to deal colors within C#, I could dive down through the namespaces to get the appropriate type by using the:
System.drawing.color;
type. In this case, it appears the namespaces are resolved at a project level and determined by the namespaces that the type is contained within. For the developer that this code targets, they get all of this in their auto-complete and aren't left searching through folders and files for that type. In C++ I might have to first include the appropriate header file, at which point I feel like we've already gone through the trouble of grepping source code for the appropriate types and finding which file includes those types. In C++ it would look like:
#include "Core/Color.h"
Color c = new Color();
The IDE offers me little help here. I have to do a directory search for the correct type. The directory paradigm seems to break down unless everyone specifically uses the right filenames and directory structure, which isn't always the case.
To fix this, it looks like not only would I have to come up with a namespace hierarchy for all of my types, which isn't such a large problem, but I'd have to also come up with a header hierarchy to eliminate the problem of constantly grepping the code to find the correct files that include those types.
Does a master header hierarchy present a problem for the compiler, preprocessor, or resulting compiled code since we'd essentially have every other header up the chain (up to a point of course) included in new files?
In the end I want a way to assist the developers who use this code by giving their IDEs a way to dive down to all the types without having to do all of the grepping that we currently have to do. There may be a way to quickly do this within IDEs already, at which point I wouldn't need to utilize the language itself to solve this sort of development problem, however I can't seem to find it.
See the following SO discussion and how this was handled by one of the SO users
C++ namespaces advice
http://www.adamjamesnaylor.com/2012/10/23/NestedNamespacesInC.aspx
I run code analysis on a project and I get a warning saying
CA1020 : Microsoft.Design : Consider merging the types defined in {some namespace} with another namespace. {some namespace}
Why do I get this? Is there a negative implication of having too many namespaces?
I believe the main reason is discoverability and believe that plays a large part in the successful support and maintenance of your code. If it's easier to discover it should be easier to maintain.
Here's the a quote from MSDN.
Namespaces should
contain types that are used together
in most scenarios. When their
applications are mutually exclusive,
types should be located in separate
namespaces. Careful namespace
organization can also be helpful
because it increases the
discoverability of a feature. By
examining the namespace hierarchy,
library consumers should be able to
locate the types that implement a
feature
There are no real negative implications at runtime, in terms of increased memory or execution times. Also, namespaces are not like IP addresses, which have a fixed pool and can eventually run out.
Namespaces are basically a naming convention to help you group related things together. The CA error is suggesting that too many small namespaces may make your code harder for other people to use.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
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?
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Assuming that the enum or struct is not nested within a particular class i.e. it belongs to the project namespace, should it be defined in:
Its own file
A general-purpose file called Enums.cs or Structs.cs where all the enums/structs that belong to the project namespace would be defined
Somewhere else...
Personally, I prefer the one type, one file philosophy. I even go so far as having nested types in separate files with partial classes used to allow the separation.
I mainly do this because I've seen far too much of the opposite. Single files that contain dozens of classes. The experience changed me.
For me, one type = one file, unless it's a delegate. I don't need to declare my own delegates very often these days due to Func and Action, but when I do I find it's useful to have a Delegates.cs file.
As for structs - I can only ever remember writing about two of them, aside from for the purposes of testing the evil things that mutable structs can do. But I'd stick to one per file there too. Why wouldn't you? Just because they're value types doesn't mean they're naturally shorter or simpler than classes. (Can you imagine if decimal and DateTime were both in the same source file? Eek!)
EDIT: I've just thought of another case where having multiple structs may be appropriate: interop. In that case I might have Interop.cs or Win32.cs... or possibly a namespace for it and back to one file per type.
This MSDN article on enum best practices makes no recommendation on where to store enum definitions.
You'll get different recommendations. Personally, I tend to store enums in the same file as the class they're related to. I like to keep my file structure the same as my namespace structure, as much as possible, and so if my enums naturally fall into a particular namespace, I'll store the definition in the corresponding file.
My suggestion is, find a scheme that works for you, and stick with it.
I put all of my enums in their own file. However, I also fully xml doccomment all of my types, including enums...so there are probably many more lines of code in my enum files than in most peoples.
I haven't written a struct in many, many years, but I don't consider them to be any less than a class (and again, I fully xml doccomment all of my types, structs included), so they have in the past always had their own file too.
When it comes to delegates, being as they are usually one liners (minus doccomment), I tend to keep them in the same file as whatever more prominent type they support. I don't often write delegates these days, but sometimes I find they still have a use. However, I try to keep any delegates declared at the top of the file, rather than nested or below the main type...makes em easier to spot when you go looking for them.
I think there is also a very simple but practical reason to keep each type in its own file. They are very EASY to spot that way. If you bury your enums and structs inside other types, or keep them within another file, sometimes (and don't assume you, and the people reading your code, always have access to Visual Studio and all of its rich tools) it can be quite difficult to find the type your looking for.