When I put a class file inside a folder, Resharper suggest me to update the namespace. So if I have the file Classes/Game.cs (Class), it will suggest the namespace MyApplication.Classes.
The problem is that I have a subfolder called Game too, that have components for the Game class. And it is confliting with namespaces. For instance:
/Classes/Game.cs MyApplication.Classes.{Game}
/Classes/Game/Version.cs MyApplication.Classes.Game.{Version}
What is the best method to turn around that?
Currently I'm organizing like that:
/Classes/Game/Game.cs MyApplication.Classes.Game.{Class}
/Classes/Game/Player.cs MyApplication.Classes.Game.{Player}
/Classes/Game/Version/Version.cs MyApplication.Classes.Game.Version.{Class}
/Classes/Game/Version/History.cs MyApplication.Classes.Game.Version.{History}
So note that I rename the "main" class to Class to avoid conflict, but I keep a more accurate name in the filename. But it is ugly, not?
First of all, a folder named "Classes" doesn't seem particularly helpful - everything is a class after all and this doesn't seem to give you any useful information.
If you wish to keep this naming scheme, then there are two options. The first is to disable Resharper's recommendations - or at least tell R# to treat them as Hints, rather than Warnings.
The second is to give your folder a name that isn't a valid namespace declaration. This will make R# stop suggesting it as a valid namespace. The format I've most often seen and used is to use square brackets around the name. So you have a folder hierarchy like this:
/Classes/Game.cs
/Classes/[Game]/Version.cs
etc. In this case, R# will suggest "MyApplication.Classes" as the namespace for both the Game and Version classes.
Start with this answer to NET: Best Practices/guidelines for dividing namespaces between files?
While every project, even every game, is going to vary as far as structure goes there are a few things that help.
The first thing you should ask is how large of a project this is going to be. If you don't know, start with everything in the root namespace of your project until you figure it out, and only then refactor. Don't waste time organizing when you could be learning, because chances are you either won't need it, or will need to radically change it once you do figure it out.
Once you know that your project is going to be large enough to require lots of namespace, you should also know what kind of structure it needs. If it's entity-component oriented, as most large games are now, you'll probably want to use a folder/namespace structure like
MyProjectName # System classes, like Game1
.Components # Base component definitions
.Controllers
.Physics
.Renderers
.Entities # Base entity definition and player entity
.Enemies
.Powerups
...
It also helps to work on other people's code. You'll learn a lot about organization from trying to locate functionality in unfamiliar code.
My strategy for organizing files is to put them not only inside of namespaces but often in subfolders that don't act as a namespace but help to organize files. I prefix such folders with an underscore _. If you're using R# you should set the folder property Namespace Provider to false. Also remember to remove the _Folder from the namespace if you add new file because Visual Studio automatically adds it.
Here's an example:
MyProject
Properties
References
_Impl
App.config
package.config
First I put the entire implementation inside the _Impl folder because I don't like files that are scattered all around the project.
Next in the _Impl folder I may use more underscore _ folders if I see no reason to create a new namespace but it would make sense to put the files together like _Exceptions or _Enums or _Attributes:
MyProject
Properties
References
_Impl
_Attributes
MyAttribute.cs
_Exceptions
MyExtpion.cs
MyAnotherException.cs
_Extensions
MyExtensions1.cs
MyExtensions2.cs
SomeClass.cs
SomeOtherClass.cs
App.config
package.config
As namespaces the underscore _ folders wouldn't make much sense but they allow to keep files together for organizational purposes.
Otherwise I would look something like this:
MyProject
Properties
References
MyAttribute.cs
MyExtpion.cs
MyAnotherException.cs
App.config
package.config
SomeClass.cs
SomeOtherClass.cs
In MyProject.Test with unit test I also use this system:
MyProject.Tests
Properties
References
_Impl // only tests
_Attributes
MyAttributeTests.cs
_Exceptions
MyExtpionTests.cs
MyAnotherExceptionTests.cs
SomeClassTests.cs
SomeOtherClassTests.cs
_TestHelpers // here I'll put any supporting classes
SomeTestHelper.
App.config
package.config
Related
My C# .NET solution files are a mess and I am trying to find a way of getting things in order.
I tried to put all close files together in the same folder I am creating for that purpose. For example, I put interfaces, abstract classes, and all their inherited classes at the same folder. By the way - when I do that, I need to write a "using" statement pointing to that folder so I can use those classes in other files (also a mess I guess).
Is there an elegant way of doing things more clean, and not a list of files that I find very confusing?
Is it a good idea to (let's say) open a abstract class file and add nested classes for all the classes derived from it?
Is there a way of telling the solution to automatically set the folder "using" statements above every class I create?
The best way is when your solution file system structure reflects your program architecture and not your code architecture.
For example: if you define an abstract class and after have entities that implement it: put them into the same "basket" (solution folder) if they make a part of the same software architectual unit.
In this case one by looking on your solution tree can see what is your architecture about (more or less) from very top view.
There are different ways to enforce the architecture vision, understanding and felling of the code file system. For example if you use some known frameworks, like NHibernate, or (say) ASP.NET MVC tend to call the things in the name the technolgy calls them, in this way one who is familiar with that technology can easily find itself in your architecture.
For example WPF force you define in code things in some way, but also you need to define byb the way Model, ModelView, View.. which you will do intuitively in seprate files. The technology enforcce you to define your file system in way it was thought.
By the way the topic you're asking for, is broad known dilema/question, not resolved, cuase the code is just characters sequence and nothing else.
Good luck.
It sounds like you're hitting the point where you actually need to break things up a bit, but you're resisting this because more files seems like more complexity. That's true to a point. But there's also a point where files just become big and unmanageable, which is where you might end up if you try to do nested classes.
Keeping code in different namespaces is actually a good thing--that's the "issue" you're running into with the folders and having to add using statements at the top of your files. Namespacing allows you to logically divide your code, and even occasionally reuse a class name, without stepping on other parts of your code base.
What version of Visual Studio are you using? One little known feature of Visual Studio is that it can automatically create the using directive when you type a class name. That would eliminate one pain point.
If I was in your shoes, I'd start looking for logical places to segment my code into different projects. You can definitely go overboard here as well, but it's pretty common to have:
A "core" project that contains your business logic and business objects.
UI projects for the different user interfaces you build, such as a website or Windows Forms app.
A datalayer project that handles all interactions with the database. Your business logic talks to the datalayer instead of directly to the database, which makes it easier to make changes to your database setup down the road.
As your code base grows, a tool like ReSharper starts to become really important. I work on a code base that has ~1 million lines and 10 or so projects in the solution, and I couldn't live without ReSharper's go-to-file navigation feature. It lets you hit a keyboard shortcut and start typing a file name and just jump to it when it finds a match. It's sort of like using Google to find information instead of trying to bookmark every interesting link you come across. Once I made this mental shift, navigating through the code base became so much easier.
Try using multiple projects in the same solution to bring order. Seperate projects for web, entity, data access, setup, testing, etc.
IF the files are in the same namespace you won't need a using statement. If you're breaking your code into multiple projects you'll need to reference the other projects with using statements.
Its up to you. Break things apart logically. Use subfolders where you deem necessary.
Not sure.
Yes, but you'll need to create a template. Search for tuturorials on that.
1) Your solution folders should match your namespace structure. Visual Studio is set up to work this way and will automatically create a matching namespace. Yes, this requires a using for stuff in the folders but that's what it's for.
So yes, group common stuff together under an appropriate namespace.
2) Yes, subclasses should probably live in the same namespace/folder as their abstract base, or a sub folder of it. I'm not sure if you mean all in the same file? If so I would say generally not unless they're very very simple. Different files, same folder.
3) Not that I'm aware of. If you right click the classname when you use it you can get Studio to automatically resolve it and add a using (Ctrl + . also does this)
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.
I am reorganizing my source files into a single solution with a single project, due to various reasons:
a paranoic configured antivirus software;
Advices on partitioning code through .NET assemblies
Control component dependencies to gain clean architecture
Benefit from the C# and VB.NET compilers perf
This leaves me with many namespaces, which are splitted across multiple files. So far, I am using this convention: given the namespace Company.Project.A, the files are named A.f1.cs, A.f2.cs and so on, and the Company.Project.B namespace is splitted across B.f1.cs, B.f2.cs, etc.
Given the single project restriction, are there any better ways to organize multiple files in multiple namespaces?
Yes - use folders.
If you create a folder within a project, new classes within that folder will automatically use the folder name as the basis for the namespace.
For instance, if you have a project with a default namespace of "Company.Project" and a folder "Foo" containing "Bar.cs" you'll end up with:
using System; // Etc
namespace Company.Project.Foo
{
class Bar
{
}
}
So the solution is right here. It's Folders. But it's sometimes tricky. First of all it's kind of a good idea to have one file per class. If you will pack several classes into one file - you'll have problems with finding them with time.
Second thing about folders - if you will click on a folder and choose for example "Add -> New Item", this item will be put into selected folder. But watch out! If you will move files between folders, namespaces are not updated.
It's common source of messing project. Just after a while you can end up with a project where you have neat organized folder and files, but not reflecting namespaces. So for example, if you have class MyClass in folder MyFolder make sure, your namespace for this class is something like MyApp.MyFolder and not some old rubbish.
So If you will not pack classes into one file and watch if classes namespaces reflect folder hierarchy - you're on the good road to make you project very easy to read and navigate.
100% agree with Jon Skeet.
To gain more overview at the folder level we're creating folders breaking the namespace structure by prefixing them with an underscore.
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.
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.