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.
Related
I just wondered what other peoples thoughts were regarding related classes in a single or separate .cs file?
If, for example, I have an interface that is implemented by, say an arbitrary 10, other classes, would you place them all in the same file or separate them?
Thanks.
I always go with separate files for each class. It's recommended best practice and it really makes sense.
My approach is that 1 file == 1 class/interface/module/... whatever.
So the filename always reflects what's in there. To me that's the cleanest approach.
I would separate classes into different files. This makes them a lot easier to find in the IDE.
I would place each class in a separate file, and the interface in a separate file as well.
I would give the file the following name .cs
That's a recommended best practice; it allows you to find your classes very fast. I always go with this approach (except when I have inner classes offcourse. :) ).
I must agree with the rest here: 1 class = 1 file.
Also use correct namespacing for full project name as well as folders. Interfaces also go into separate files, but I usually keep enums and structures inside other classes.
Folders can be used to group certain classes together. There is however a small issue when you "run out of names" so to speak.
Example:
Solution: Tedd.CoolApp
Project: Tedd.CoolApp.Engine
Now what do I name the class? I want to name it Engine, but that would give me Tedd.CoolApp.Engine.Engine... :)
The computer could care less about the folder structure you concoct, so this question definitely falls under the category of code readability. As mentioned in this post about standards of code readability, friendly naming, consistency, and logical code separation are fundamental to the creation of readable code.
So, where does that leave us? The creation of files--and the creation of namespaces and file regions--should be consistent. The names should be understandable. And the code in each aggregate category should have something in common, as should be detailed in the category name. Ultimately, with readability, you're considering that your code might be inherited by another poor fellow, and that the naming standards that you've created might help that poor fellow (a "tourist developer", if you will) more easily navigate around in the madness.
That's a lot of talking, so let me get down to brass tacks. These are my rules, but I think they might be helpful to those who are looking to clean up their own code aquariums:
Place one class (or one interface, enum, or struct)
in one file.
The name of the class should be the
name of the file.
Classes that inherit from the same base class should be in the same folder.
If at all possible, a class should be in the same folder as the interface that that class implements.
An interface should have the same name as the class, but should be prefixed with a capitalized "I". It's the only bit of coding advice I still respect from the Hungarians.
The folder name should be a pluralized version of the base class. For example, if we're creating a bunch of Engines, Engine should be the base class name, Engines should be the folder name, and all of the classes that inherit from Engine should be in the Engines folder.
The namespace structure should directly follow the folder structure. So, the namespace for a given set of Engines (example from above) should be placed into a namespace called Engines. If Engines is a subfolder of a subfolder, each subfolder should be its own sub-namespace, e.g. Project1.Subfolder1.Subfolder2.Engines.
When you're dealing with partial classes that need to live in two separate folders (as one piece of the class is autogenerated), place the non-autogenerated class into a folder suffixed with Extensions. In the file, comment out the Extensions namespace like so: namespace FatDish.Engines//.EngineExtensions { ...
When it comes to navigability, the first and second rule are key, as they directly aid in indicating to the "tourist developer" where any given piece of code resides.
That's all I can think of at the moment. It's more important that you're consistent in your conventions than it is that you adopt any particular form of conventionality. That will help other developers understand and consume your code at a quicker rate, and ensure that future developments in the project (written by folks other than yourself) stay within the same conventional, coherent bounds that you've established.
Hope this helps!
Personally I adhere to Single Responsibility Principle where each of my classes has a single behaviour
think of a ecommerce site that has
User Registration
User Login
billing
Supplier Ordering
I would separate these out to a User class, Billing Class and Orders class - the same would then adhere for an interface driven approach - 1 interface for each Responsibility
check out SOLID design principles - each class would then be in owns own file and have a suitable naming convention to help
I am trying to get a handle on the best practice for code
organization within my project. I have looked around on
the internet for good examples and, so far, I have seen
examples of a web project with one or multiple supporting
class libraries that it references or a web project with
sub-folders that follow its namespace conventions.
Assuming there is no right answer, this is what I currently
have for code organization:
MyProjectWeb
This is my web site. I am referencing my class libraries here.
MyProject.DLL
As the base namespace, I am using this DLL for files that
need to be generally consumable. For example, my class "Enums"
that has all the enumerations in my project lives there. As
does class MyProjectException for all exception handling.
MyProject.IO.DLL
This is a grouping of maybe 20 files that handle file upload and
download (so far).
MyProject.Utilities.DLL
ALl my common classes and methods bunched up together in one
generally consumable DLL. Each class follows a "XHelper" convention
such as "SqlHelper, AuthHelper, SerializationHelper, and so on...
MyProject.Web.DLL
I am using this DLL as the main client interface.
Right now, the majority of class files here are:
1) properties (such as School, Location, Account, Posts)
2) authorization stuff ( such as custom membership, custom role,
& custom profile providers)
My question is simply - does this seem logical?
Also, how do I avoid having to cross reference DLLs from one
project library to the next? For example, MyProject.Web.DLL
uses code from MyProject.Utilities.DLL and MyProject.Utilities.DLL
uses code from MyProject.DLL. Is this solved by clicking on properties and selecting "Dependencies"? I tried that but still don't seem to be accessing the namespaces of
the assembly I have selected. Do I have to reference every
assembly I need for each class library?
Responses appreciated and thanks for your patience.
It is logical in that it proceeds logically from your assumptions. The fact that you are asking the question leads me to believe you might not think it is rational.
In general, things should be broken down along conceptual boundaries rather than technical ones. MyProject.IO.DLL is an example of this principle surfacing in your current design. All of the IO things logically go together, so they end up in a single binary. Makes sense.
Breaking things down into namespaces based on their technical type - enum, class, etc. - is going to be a little more problematic.
The dependencies problem is the same one you'd have breaking one class up with many and it is resolved using the same technique: inversion of dependency. Where two things seemingly need to depend on one another, add an intermediary thing that represents the contract between the first two. This can be abstractions, constants, mediators etc... whatever you need to make it so that instead of thing A depending on thing B and thing B depending on thing A, you have things A and B depending on thing C.
I've got a bit of a conundrum on my hands.
I'm currently compiling a load of 'code snippets' into reusable libraries that I obviously intend to use in multiple applications.
I'm having trouble deciding on an appropriate namespace and assembly name.
Basically, I've currently got JasonSummers.Validation as an example for my validation library, since I have no 'company' and no specific project which the code applies to.
However, later on, when I come to use said namespace in a client's project, I don't think it's really appropriate to have my name referenced in code which they will probably own the IPR for.
I would just use 'Validation' as the namespace (after all, StructureMap is StructureMap, not JeremyMiller.StructureMap) but this may cause confusion for future developers as 'Validation' is used in the 'System' set of namespaces provided by .net
All comments greatly appreciated.
You can always use name from biology e.g Tribulus. or any other for your root namespace. So your code goes into e.g Tribulus.Validation or Tribulus.Utilities etc. Toplevel namespace need not to be a functional name. It can be just a signature of a company or just a unique interesting name as i mention.
In my personal experience, I maintain a code base for that useful functions at source level, i.e., I copy every function I need in every project, under my client brand and assembly name.
I didn't found be useful to keep that functions at assembly level, exactly because that: it'll contain some names which can generate confusion and for an extra reason: a client paid for some functionality, but not for another (include in a general assembly). So, I just pack what he/she bought.
An option could be to use a neutral name, like Reusable and to merge your utility assembly by using ilmerge framework command.
Take a look at Microsoft's Namespace Naming Guidelines
I got it as an answer from Konamiman to my question which is related to yours.
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.