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.
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
we are changing the name of our product, so i also want to rename the namespaces of our
framework-classes. But now i have the problem, that i don't know in which programms and scripts our namespaces are used. Is there a way in c#, to locate the same class in two different namespaces?
I know the solution, that i could inherited from my classes in the new namespace, but this is a very bad solution i think. So I have no idea how to solve this problem, because simply renaming all namespaces doesn't help and will cause a lot trouble.
Thank you!
If external scripts are referencing your assembly using the old namespace names then those names will have to remain in your assembly in you wish to continue to use those scripts. If you also want to create new namespace names to reflect the new name of your product, those names will also need to be hardcoded into your assembly. This will inevitably lead to problems!
I would recommend one of the following:
Leave the namespace names as they are.
Rename the namespaces in full and update the Python scripts at the same time.
I would definitely not recommend the faux 'inheritance' method, or any other solution which results in duplication within the assembly.
You could search the whole project / solution of course, but that seems sort of messy and time-consuming too, if you've got more than a trivial project.
Are you using Resharper? For this type of task, you definitely should be. If so, there is a chance this could at least help you on your way:
Rename the folders your source files are in in the Visual Studio Solution Explorer (this should in theory be easier than looking at each source file one by one, right?).
Now open one source file that you know will have the wrong namespace due to a renamed folder. It should appear with a blue squiggly line, as in the picture below.
Use the Resharper tip (pyramid to the left, or Alt + Enter) to open the context meny thingy also shown below.
Select Find all issues of this type in scope, and select Solution as your scope. That might at least help you get an overview of which classes you need to change the namespaces for, and go through them and change them systematically.
As for your scripts, I would guess that you best bet is to do a plain text search for the old namespaces - possibly a search and replace. Perhaps you can include your scripts in a VS solution, and use the built in search there to scan and fix them. That might at least ease the pain a little..
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 9 years ago.
Improve this question
Not sure if this follows the rules or not, but I need some help with names. How should I approach project name vs namespace vs class. For example, I want to make a datacleaner program. So I name it Datacleaner, and then DC for the class, and then Cleaner.cs for the file name, and it just gets all confusing. Is there some best practice I can be following here!? A helpful mindset or naming theory would be exceptionally helpful.
It is slightly off-topic, but I'll give you a shot here.
The first thing we need to look at, is the root namespace. Depending on what you're doing, this root-namespace may be shared across multiple projects. A good example of this is System. You might put your company name there, or you might choose something more eclectic. If I am writing library code, I avoid things like DataCleaner because libraries are supposed to be generic and don't pertain to a common form.
So, you're writing a data cleaner. Great! There's nothing wrong with having a common library and having a Data namespace (maybe you want to add more things pertaining to data in the future), and then you have your Cleaner class.
If I were a user of your API, I'd happily understand that <library>.Data was a namespace and I need to be looking for Cleaner.
Microsoft has an excellent set of guidelines - See the next link:
Guidelines for Names
Also see the Naming section
I think you'll find there all the info you need.
This question already asked in StackOverflow, see here
You should Mike Roberts' series on How to Set Up A .Net Development Tree. It's a bit dated, but the concepts still hold true. Links to his articles are in my answer here: https://stackoverflow.com/a/9982500/467473 (he seems to have rearranged his blog and broken the links therein, though the content is still there). Also see Tree Surgeon, a tool for creating solutions using the principles Mike Roberts espoused.
In a nutshell, lay out your source tree thusly:
Fundamentally, your directory structure should look like this:
Meta/Development RootUsually mapped to root of source control system.
SolutionOne directory, contain your entire solution. Should be named to match the solution.
Solution.slnThe solution file itself.
nant.buildThe nAnt build file for the solution.
libThe lib directory contains 3rd party assemblies/dlls that are referenced by the different projects in your solution. It is under source control. Project references should point here.
toolsThe tools directory contains all 3rd party tools required to build your solution. It, too, is under source control. The tools directory should contain the versions of nAnt, nUnit etc. used by your project — and your build scripts should reference these, rather than the version(s) installed on a developer's machine.
binThe bin directory contains the output of the build process for the solution. Each projects must be configured to point here.
debugdebug build
releaserelease build
objIn the ideal world, each project's obj would be pointed here as well as this has no place in the source tree. Sadly, Visual Studio doesn't offer an official way to do that (though, I'm told, VS can be hacked to do so if you're resourceful enough).
srcThe src directory is the root directory for the actual source code of your solution.
project1The directory for project1.
project.csproj`The project file.
*.cs, etc. files. The source files.
...
project-n
The src directory contains the actual source code. Each project should be named with its full namespace. Whether you lay them out flat or build out the whole namespace structure in the file system is up to you. The idea is that the namespace should guide you to the source file.
Here is a short summary of conventions from another SO question:
Naming Convention in c#
The other answers here are all spot on, for C# you probably want to follow the naming conventions put forth by Microsoft (and are automatically used by default if you are developing with Visual Studio) unless you have a compelling reason not to.
Project Namespace should match the Project Name or should match the Project Name with some standardized prefix prepended.
Conventions for class and files are 1 class per file and the file name should match the class name.
You are forbidden to name give a class the same name as it's namespace, which I assume is the issue you ran into that prompted this question. The solution to that is probably to give the project a more general name.
To give a more concrete example of what we do where I work.
Any product we produce here we typically have a solution with two or more projects in it.
The default namespace for any project follows: ...
If the DataCleaner product had a windows service and a command line tool that dealt with the same domain you might have three projects: Console, Service, and Domain with name spaces of
Company.Team.DataCleaner.Console
Company.Team.DataCleaner.Service
Company.Team.DataCleaner.Domain
For naming of classes (and by extension the files they reside in), if you follow the above scheme you already somewhat get around the problem of having a DataCleaner class in your DataCleaner namespace, but you may find application of the Single Responsibility Principle useful. To put it simply, any class should only do one thing. If you have a class named Cleaner or DataCleaner they might be trying to do too much, and breaking it up would result in names specific to the resulting classes
I have two VS C# projects (specifically, for an Outlook plugin) that I believe to be very similar with the exception of perhaps 100 lines of code. I'm slightly worried that there might be other configuration options for the project that are different, so I'd like to compare those two.
What is the best way to see the differences between the two codebases?
I've tried putting the two projects in parallel directories and using diff, but since the projects are named differently, some of the files don't match up. I'm just wondering if there's an easier way to do this?
It sounds like you need something like WinMerge to go through and point out the differences between the two projects. It's free, and I know you can compare folder contents with WinMerge, so that's probably a good place to start. Run WinMerge on the project folders and it should generate a detailed comparison outlining the differences between the files.
See this tutorial on comparing folders:
http://manual.winmerge.org/CompareDirs.html
I strongly recommend Code Compare (not affiliated, just a happy user) for this kind of job - there is a free version and a more advanced commercial version.
It integrates nicely with VS and has syntax highlighting for C#, C/C++ etc.
One way: Make copies of both projects, rename the files and folders in one to match the files and folders in the other, then use your favorite folder compare tool to compare the two.
This won't help you unless there was a true copy-and-paste relationship between the two projects.
The better way would be to use refactoring. After creating unit tests for both projects and achieving an adequate level of code coverage, go class by class and method by method using refactoring to try to make pairs of methods identical. You may then identify methods that should be pulled into base classes or moved into other classes.
Eventually, you may find pairs of classes which are identical. Move those classes into a common library, then rename all uses of one of the classes to be a use of the other. Then delete the one no longer used.
Repeat until there is no more duplication.
If you've got modifications like renames or partial code moves, importing both versions into a single git repository (as two different commits of a single directory) could help. Git tracks contents of files, not the files themselves, so it is possible to find out e.g. a function that has been moved from one file to another.
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?