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.
Related
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.
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.
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.
Are there any best-practices that state custom code shouldn't be placed in a System namespace? Should System and its children be reserved for Microsoft code?
I ask because I'm writing a class library that will be used across many projects and I'd like to keep things consistent by placing it in System.InteropServices (since it deals with P/Invoke).
It's not a good idea because it defeats one of the primary benefits of namespaces: preventing name clashes. What if a newer version of the framework introduced an identically named type in that namespace?
This is particularly bad for System namespaces since they are imported in many other pieces of code with using directives and introducing custom types in those namespaces pollutes the naming scope of other source files with unexpected identifiers.
To categorize your custom interop related types, you can create a new namespace like MyProduct.InteropServices.
If you place a new class in System.InteropServices, every file that has a using System.InteropServices; clause is forced to have your class in scope, which may confuse the programmer. Since the programmer cannot defend oneself against this, I'd consider this bad practise.
I disagree with everyone.
I think that in a limited subset of cases (mostly with extension methods) it is perfectly reasonable to place code in a system namespace.
Here is my side of the argument from an email thread we had debating Extension methods in the System namespace over at EPS:
Ok, so here's my side of the argument:
I really like to minimize code. That includes usings.
Yes, ReSharper picks up extension methods and adds the usings for you but some people don't have ReSharper, and besides, I prefer Coderush which as of yet does not actually (as far as I know) pick up extension namespaces.
There are at least two different types of extension methods; ones that are helper methods for our application - including domain and application-specific helpers, and ones that encapsulate features and syntax that we believe the language should have had to begin with.
A good example of the latter is the ability to do "a {0} {1}".Format("b", "c") or someListOfStrings.Join(", ") rather than having to do String.Join(someStringList.ToArray(), ", "). Other more debatable examples are IEnumerable<T>.ForEach and the IsNull() extension to take the place of the clumsy object.ReferenceEquals(null, someVar) syntax.
My argument is, that there is every reason to place this latter classification - your team broadly agrees should be in the language but aren't - in the appropriate namespace (System, System.IO, System.Linq, etc.). We want those functions to be available everywhere, just like we prefer the foreach and yield keywords to always be visible. If it is application-specific however it should go in its own namespace. 90% of the time application-specific helper extensions should likely not be extensions and not even be static. I exclude from this statement using extension methods to provide aliases for function names.
You can get in some trouble with this of course when calling into assemblies that contain system-wide extensions. Suppose that I was referencing the assembly containing my void IEnumerable<T>.ForEach method and wanted to create my own ruby-like R IEnumerable<T, R>.ForEach (which is actually just a Select, but nevermind that). This would be a problem! What I like to do to mitigate the issue is to define my extension classes as being internal so that they can be used only on my project. This solves the problem nicely.
I'm having some problems to come up with a sane type naming scheme for our new line of applications. I want to follow the .NET Framework Developer's Guide - Design Guidelines for Developing Class Libraries, but I'm starting to wonder if that's such a good idea.
I'd like to use the Company.Product.Feature namespace scheme as a basis.
Problem 1: We have our own control and form base classes, and I want these to go into the Company.Product.Forms namespace. However, according to the guidelines, we shouldn't let our type names be Control or Form, even if they are in our own Company.Product.Forms namespace, since they will clash with system types.
Problem 2: We have some distinct feature areas in the application and I want these to go into their own Company.Product.Feature namespace. Lots of these features have similar design, with a controller and some views, so under each Company.Product.Feature namespace I'd like to have types named Controller, SomeView, AnotherView, etc. However, according to the guidelines, we shouldn't have the same type names in different namespaces.
The only solution I see to overcome these problems is to prefix the types with something that in some way makes the namespaces redundant. Or not?
Microsoft clearly favors some redundancy. A common example is:
System.Xml.XmlDocument
General class names, even bound within a proper named namespace can cause headaches for the many programmers who like to avoid fully qualifying their class instantiations. "Document" could be an Xml, Html or word document. This ambiguity will cause endless confusion if you happen to import more than one namespace with a "Document" class.
I'd prefer Company.Product.UI, for some reason. I would use that naming for the web, too.
Regarding problem 1, if these are base types, you might include Base in the class name.
Then, you typically have a set of domain specific controls, which won't clash with built-in types.
If you also keep wrappers for common UI controls(TextBox, DropDownList etc), then i would actually recommend use a prefix for them,
maybe this prefix is an abbreviated name of the product.
And then, if you do that, then you might want to be consistent, and do it for all types,
regardless of whether they are ambigious names or not.
I tell you from my own experience.
You'll end up constantly hovering over variables to see their full type names, etc, you will use aliasing etc..
The code will be harder to read.
Problem 2: While at GUI layer, i tend to break these rules, because you will want naming consistency(common verbs; Show,Edit,List). If the guideline tells you otherwise, i would believe it is because it is simply not specific enough.
First post here in StackOverFlow, on an old question. Please, be kind with me :)
General class names, even bound within a proper named namespace can cause headaches for the many programmers who like to avoid fully qualifying their class instantiations. "Document" could be an Xml, Html or word document. This ambiguity will cause endless confusion if you happen to import more than one namespace with a "Document" class.
Microsoft MIGHT sometimes favor some redundency but it's not always de case.
As for the Document vs XMLDocument problematic, when you know there might be more than one type of document, why not just include the qualifying part of the namespace in the declaration?
For example :
Xml.XmlDocument
vs
Html.HtmlDocument
Instead of importing the XML and HTML namespace, why not just include the containing namespace? It would become like this :
Xml.Document
vs
Html.Document
If it makes logical sense, then do it. They are just guidelines, not the LAW. (not that you cant break that too.)
Having classes in the with the same name in different namespaces is just is against the guidelines for a reason, it makes reading the code just a little bit harder because when you see "Controller" you have to mentally map it to "Feature1.Controller" or "Feature2.Controller".
I would prefer to use Company.Product.Features.Feature1.Feature1Conroller with the redundant information or maybe Company.Product.Features.Feature1Controller if it bothers you (and I personally don't like having too many namespaces).
But feel free to break the guidelines, rules are there to make you think before you break them :-)