I am working on a simple project and I have created several classes, interfaces, one static class and so on. What I am asking is, how to organise this files into namespaces. Is there any good practice for this or I should just follow the logic of my program. I am currently thinking that I should move the interfaces into one namespace and all the classes into another. So what can you advise me. I am really curious to find out the best way to separate my files.
Have a nice day :)
You should group your code in namespace with other types which have the highest cohesion. That is, group types together when they perform common functionality. The type of cohesion you're suggesting is logical cohesion, and is really a rather weak form of cohesion.
Namespaces are mainly for the benifit of large projects. Since you are working on a "simple project", I suggest that you use a single namespace for the entire application. Since everything in C# must be a type or a member of a type (i.e., there are no global variables or methods), the types that you create (objects, classes, interfaces, enums, etc.) are usually a good-enough organizing feature for a small project.
For slightly larger projects, I suggest putting each tier into its own namespace.
For even larger projects, namespaces should be a logical grouping of related types or subsystems, according to preference.
Into specific namespace you should put everything which concerns some matter. For example all the stuff concerning string manipulations you should put into separate namespace, e.g. com.server.string.
It's very important especially in case you have class with names existing in other namespaces.
The only reason to split your code in files is to make your code maintainable.
As a general rule of thumb, I tend to create folders for enum's, struct's, models, controllers, etc. Depending on the size of the solution, you keep nesting in groups after that.
Sometimes it makes sense to just put the entire namespace in the file, other times, you let your nesting take care of the naming.
A good rule of tumb is that you should be able to find what you are looking for quicky, and, more importantly, someone who hasn't seen the project, should find his way around quickly.
One thing to keep in mind is that you never put more then one thing in one file. Never put two classes in the same file, never append enums at the end of a class file, etc.
You are confusing files with classes. You can create folders in Visual Studio to organize your files. That way you can group interfaces and classes (which is what I usually do). VS will automatically put new classes for which the file is in those folders in the namespace of the same name. This is usually not what you want (I don't know how to turn it off, so I can't help you with that).
I agree with the other answers here that you should group types based on what they do, not on what kind of language construct they are.
Related
Is it safe to put every form in my presentation-layer in the same namespace? (Might be a stupid question but i want to be sure).
Namespaces are to organize your code. If you have a few forms and you put them all in the same namespace, that is okay.
I would say if you have tons of screens, you eventually will lose overview of the code, and then it becomes important to organize your code. Usually you will split on funtionality, like DataLayer, PresentationLayer, etc., but you can do that for screen categories too (like User, Article).
To be clear, there is nothing safe or unsafe about using namespaces.
It's not unsafe.
The purpose of namespaces is to:
avoid running out of names (which must be unique), and
avoid confusion between similarly named things.
For example, there are lots of things in lots of libraries with classes called "Node", "Record", "Entry", "Rule" or similar generic terms.
In general, if you always use two classes together and never apart, there is usually no reason to put them in different namespaces.
I was often wondering about the right way to do this:
For example, in my program I have around 100 constants (or enums) that are used in some calculation. They should preferrably be stored in one place. They can be grouped hierarchically, for example:
System3 / Rules / Rule7 / ParameterXY / MaxAverageValue
Naturally, I want those values to be accessible while coding, so storing them in some kind of ressource is not really an option.
As far as I could tell, this can be done with:
very long constant names
nesting classes
namespaces
Using names is quite ugly, and it's not really well maintainable. I find nesting classes a nice way to do it, but some stylecop/fxcop rules forbid that, so this must be "bad" in some way. Lastly, I find the suggested alternative, using namespaces, not terribly nice neither. Imho it creates masses of folders and files that each contain almost nothing. And I don't like when 50 sub-namespaces pop up in the assembly reflector.
So.. how do you do this kind of task? What would you suggest?
very long constant names
This is sort of gross, but at least it is discoverable. All your code would reside in the same place so you wouldn't have a problem finding it.
I find nesting classes a nice way to do it, but some stylecop/fxcop rules forbid that, so this must be "bad" in some way
One reason it is is bad because automated code generation/code inspection tools are harder to work with. Another reason is that it is harder to discover these with Intellisense.
The most important reason this is bad is because a nested class should be strongly associated in an object-oriented dependency sense for the layout be make sense logically. In all but some rare cases (e.g. Enumerator classes) it won't make sense. In your case it also doesn't make sense because your classes don't really have any behavior or object orientation at all - they're just a hierarchy of constants.
Namespaces
For the problem you described, this is the best way to handle it. You get the least clutter per-level, and you get Intellisense while typing so you can see what you're narrowing down to while descending through the hierarchy.
Imho it creates masses of folders and files that each contain almost nothing
If you really need a huge pool of constants, and it doesn't make sense to bind them to other parts of your application, then this is one of the rare cases that I'd abuse the one-file-per-class and one-folder-per-namespace rules. The only reason you're even stuffing them into classes at all is because .Net doesn't have support for global variables.
Another suggestion
Do you have domain-specific objects that these constants belong on instead? E.g. is there any logic related to the System3 / Rules / Rule7 class? Is that not some sort of actual business rule that you should embody with its own class?
If you can arrange your code so that you have a thicker domain model, then the most logical place to put your constants is on the classes that embody the corresponding domain logic.
If it doesn't make sense to have a thick domain, you have fully generic rules processing, and you are relying on constants to feed your business engine logic, then you have a data-driven application. This means you should store your data in configuration files, not in code.
How often is each constant re-used in multiple methods? You could consider reorganizing your constants. If you still find yourself with huge numbers of constants, try putting them in a static class with read-only properties.
If you just need a good place to look at them all in one place, you could also look at storing them in the app.config file and you can access them through AppSettings and the ConfigurationManager class.
Well the way I do this is to have a sealed file called Constants.
so
public sealed class Constants
{
//for e.g.
//Sessions
public const string APPSESSIONKEY = "AppType";
}
Than I use this in the rest of my project and the importance here is what you will name it as it will help you remember it and make sense when you need it.
By calling it in your code.
Constants.AppSessionKey
You could also
Create an Assembly whose only purpose is to hold constant values for the project. Every other Assembly should then reference this one. Following DRY and KISS, since adding references is simple enough. Main problem here is recompilation.
We use Resources files with a custom T4 template that generates a static class hierarchy with readonly string fields for the values.
The keys in our Resource file are separated with '.' to build the hierarchy.
We can have separate resource files that are compiled into one class hierarchy.
I know that nested classes is not recommended but in my opinion, for a situation like this it is the nicest solution.
If I'm dealing with one class and one public struct (not nested), Should I create a separate .cs just for the struct? Or leave it un-nested in its .cs file of the class? (This is assuming the struct relates to the class, but isn't so exclusive to the class that it should be nested and declared private)
Edit: I removed my initial question about two classes because I found C# classes in separate files?
Note that the only person(s) that can accurately answer this question is you, and your team. If your team is happy to find several related types inside a single file, combined due to ... whatever... then what I, or whomever other person, says, should be just ... irrelevant.
In any case, I would turn the question upside down:
Is there any reason to place two separate types (related by names, functionality, or whatever, but separate nonetheless) in the same file
and I've yet to come up with a good reason.
There are extensions/addins to Visual Studio where you can type in the name, and quickly navigate to the file, and I can think of three, but there are undoubtedly others:
DPack
ReSharper
CodeRush/Refactor! Pro
The first allows you to quickly navigate to a file by name. If you know the type, but have people putting multiple types into the same type, this will not be helpful, at all.
The second and third, lets you navigate to a type by name, but you shouldn't rely on people having those, or knowing how to use them.
To that end, I would advocate following these rules:
Project names should be identical to the root namespace of that project. I differ from this point myself where in some cases I name my projects "...Core", and I then remove "Core" from the namespace, but otherwise, leave the project name identical to the namespace
Use folders in the project to build namespace hierarchies
The name of a type should correspond 100% to the name of the file + whatever extension is right for your language. So "YourType" should be "YourType.cs", "YourType.vb" or "YourType.whatever" depending on language
That depends on who you ask.
I, personally, find it easier to read if they are all, always, broken out. However, the compiler doesn't care... so whatever you and your team agree is easier to understand.
In my opinion it's a good practice to avoid that. Some day a developer will be looking around for ClassBar in the project and won't be able to find it easily because it's nested in ClassFoo.cs
Tools like Resharper have a neat feature where you can just select a class, right click, place in new file to make this easier.
If you read any of the popular coding standards (Lance Hunt, iDesign, Framework Design Guidelines etc) most of them advocate 1 class per file.
Its annoying to scroll down and search for how many class each.cs file contains/hides.
Maintainability issue while using version control
Usability with our team.
Check here for more interesting discussion on same.
I think it was less about whether you can or whether you should. For things like this, I feel it's best to look to the convention in the rest of the codebase. Sometime conformity is better because it makes other developers jobs easier becaues everybody knows where things are.
If it's entirely new project and you are setting the standards here by yourself, do what makes sense to you. To me if the struct has no use outside the related class, I may put them in the same file. Otherwise, I seperate them out.
I have a directory structure to store the source files. Is this the good practice to
name the naming space according to the directory structure?
Like
Models\model.cs
Data\data.cs
One is defined in namespace Models
One is defined in namespace Data
Yes, that's the typical approach, and it's also one that's supported by tools such as ReSharper.
The difference between this and the Java approach is that you don't add directories all the way down from the top - just from the default namespace for the project. So for example, suppose we were creating Foo.Bar.Baz.Model and Foo.Bar.Baz.Data, the C# and java solutions might be:
C#:
Foo.Bar.Baz
Foo.Bar.Baz.csproj defining a project with default namespace of Foo.Bar.Baz
Model\
SomeModel.cs
Data\
SomeData.cs
Java:
src\
foo\
bar\
baz\
model\
SomeModel.java
data\
SomeData.java
yes is the usual practice, but you also put the project name before the directory name so you will have: myclasslibraryname.Models.Model and myclasslibraryname.Data.Data
Yes. It is a common practice in Java (at least, the source code I've looked at for big projects has almost always been structured this way). Not as common in C# from what I've seen, but there's nothing keeping you from doing it, and it helps you find the code a lot faster.
You'll probably want a deeper namespace hierarchy than just one level though. It is common to preface it with your organization or group name, the project name, the library/program name, then code architectural names (like Model, View, Data, etc). Whatever makes the most sense for whatever scope the source code of your project will live.
Generally I think it is a good practice. When you do it in such a manner, while going through the code, you can generally associate or easy to locate and get to know where your code file is coming from.
This is also a good practice in terms for maintaining the code. Some new user comes in, he can just see the namespace and identify where the code files are located or needs to be searched.
I don't know really if this is good or not.
But I name it like this.
I defined categories for the different modules.
Like this:
Company.Common
Company.Common.Web
Company.Windows
Company.Windows.Services
Common represent a directory. Inside it I created a solution with VS2010.
Inside the solution I create a project for each part and therefor the subdirectories for the project and if the project is complex, more sub dirs for the existing classes inside the dll.
There I have a good overview in all views (dir - view and project view - code view ).
This is a convenient convention for many projects, and one which some tools support or expect.
However, this isn't the full story. Although it's a good default, I don't think it should be regarded as inviolable best practice, because there are some circumstances which might motivate doing things another way. Additional factors to think about include:
Unnecessary namespace proliferation
and deeply nested namespace
hierarchies can be a pain for users
of your types. In a large library you
may want to start organising the
source code files into some folder
structure before you feel the need to
impose multiple namespaces on your
clients.
Related to this, namespace
hierarchies in .NET are supposed to
work such that dependencies between
types go from child namespace to
parent, not the other way around.
This isn't always the natural way to
organise source code into
folders/directories. For example, one
often sees people creating namespaces
such as MyNamespace.Foo.Common
containing utility types used both by
types in MyNamespace.Foo.Bar1 and
those in MyNamespace.Foo.Bar2. It
seems sensible to them at the source
code organisation level, but it
breaks the namespace dependency
convention.
Sometimes you may want to provide
additional functionality by adding
some types to a library namespace by
distributing a supplementary assembly
rather than releasing a completely
new version of the full library
assembly. It's likely to be more
convenient to keep source code files
for the respective assemblies
separate from each other in the
repository, rather than to store them
together just so as to keep all types
for the namespace in the same folder.
In short, I'd say follow the usual practice unless you have a good reason to do otherwise. But don't let it deter you, if you have a good reason to make use of the fact that Namespaces can provide a grouping of types completely orthogonal to their grouping into deployable assemblies and the source code which builds those.
Should my interface and concrete implementation of that interface be broken out into two separate files?
If you want other classes to implement that interface, it would probably be a good idea, if only for cleanliness. Anyone looking at your interface should not have to look at your implementation of it every time.
If there is only one implementation: why the interface?
If there is more than one implementation: where do you put the others?
If by different files you mean different xxx.cs files within your assembly, then normally due to my own practices I would say yes - but this is down to the house standards you use. If you're just programming for yourself, then I would say this is good coding practice, it keeps everything clean and easy to read. The smaller the blocks of code in any given file, the easier something is to follow (within reason), obviously you can start getting into partial classes where things can start getting ridiculous if you don't keep a reign on it.
As a rule, I keep my projects in a logical folder structure where portions of the project might be allocated into folders DAL or BM and within there I might have a number of logically named folders which each contain a number of files: one interface, one implementation and any helper classes specific to those.
However, all that said, your team/in-house best practices should be adopted if you're working within a team of developers.
Separate files... FTW! You might even want to create separate projects/assemblies depending on how extensible your code is. At the very least it should probably be in a separate namespace.
The whole point of an interface is so that the code that uses the interface doesn't care about the implementation. Therefore they should be as loosely associated as possible, which they won't be if they are in the same file.
But as #balabaster notes, it depends on what your team's practices (although they are not always "best practices") are.
Yes, for the classes they're called partial class,
take a look link text
General rule of thumb, yes. An Interface means it may be implemented by other classes, it is cleaner and easier to manager when they are clearly in separate files.
What's more, depending on the level of separation and isolation your application is going to take, you would even want to place your interfaces in its own project. Then consuming projects would reference the interface project instead of each and every assembly that carries implementations of that interface.
Yes, even if one gives counter arguments such as there's only one implementation or he/she foresees that there will be only one implementation for a long time or he/she is the only user/developer, etc. If there are multiple implementations, multiple users, etc, then it's obvious that you would want to keep them in separate files. So why should one treat it differently in the case of one implementation only?