Multiple classes in a single .cs file - good or bad? [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is it a bad practice to have multiple classes in the same file?
Is it advisable to create multiple classes within a .cs file or should each .cs file have an individual class?(Class file name also Animal.cs)
public class Animal
{
}
public class Person
{
}
public class Utility
{
}

Simply say good practice is one class from one file. BUT if your application is quite small you can use several classes in one file.

When designing classes we respect the Single Responsibility Principle. Reading code becomes a lot easier if its shape follows its semantics, hence splitting files by class is sensible.
However if there are inner classes it makes sense to keep them in the same file
Source: Old Post

For the sake of making things simple, you should probably put them in different files. I can't think of any advantages of keeping them in the same file.

It depends about your application. If it is a big application, I think that isn't good. Data must be very organized.
I think that is better to keep them in different files.
But, if you are working for a small application, it is good to keep them in same file.
Hope that I helped you.

Logically its depend on your scope of application.
But Normally best practice to do coding in seperate class (New File , new class )
Splittting files will be more sensible.Because industries follow ths standards...

Related

Service Layer and Simplifying Classes

I have a question regarding the structure of my code and how to keep classes simple. I am working on simplifying the service layer of a C# project. Much of the code has not taken into account OOP practices and there are few classes with methods over 200 lines. I have begun to extract out smaller methods but have a quick query regarding how to do this.
As an example, i have a method that retrieves file directories that are specific to a customer, then checks to see if they exist, creates them if they don't and finally returns an object with a list of these directories. I want to stick to the principle of not having private methods and extract out into new classes though traditional i would have created private methods for checking if directories exist, another for creating them, a third for retrieving the folder names and returning the object and a public method to call all of these in order with an associated interface with a single method.
Should i be creating new classes for each of these private methods and if so would they all need an interface? or perhaps keep them all public and call them from elsewhere?
Thanks in advance!
Short answer: you should do neither of those things.
If you want to approach the problem from an object-oriented perspective, forget for a while what the methods are doing. Think about what the code is about. You only mentioned "Customer" as a possible "business" relevant thing. Try to come up with other business relevant things. What are those files? Reports? ActivityLogs? Messages? CreditReports :) ?
The point is, object-orientation is not about just having methods in different classes. The classes and the methods must have some business meaning. If they don't mean anything, then there is no real reason to have them in the first place!
From that it is also clear that "StorageManager", "StorageUtil", and things like that shouldn't exist, because it doesn't have any business meaning at all.
So start with finding out what the application is about (the things), and then you can move certain responsibilities to the appropriate thing.

Coding style with generics and inheritance [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to name C# source files for generic classes
We are currently re-evaluating how we do generic classes when we inherit from a general class. Currently we will put the following two class definitions in the same file
class Foo
{
// code for class
}
class Foo<T> : foo
{
// code for class
}
My question is a simple one, should we keep them in the same file, or split them into separate files?
So far the pros to keeping them in the same file is that you have all the code there right infront of you. The con is that when both classes get sufficiently large, it could become un-readable.
What I would like is good reasons as to why we should do one or the other. If you recommend separate file, I would also like you to include possible naming conventions, or a strategy to get around the fact that we can have only one file named Foo
This is a matter of opinion, but I'd keep them in the same file rather than try to maintain some naming convention for one or the other.
While I subscribe to one class, one file, I think there is value in having these together. We really treat these as one class, right? Typically, Foo will be abstract, and is just a way of using our generic types… well, more generically -- in places where the type parameters don't matter and can't be known at compile time.
If the classes become too large, it should be a red flag anyway that some responsibilities should be broken out.
Unless classes are utterly trivial, I never put more than one in a single file. It's much easier, IMO, to find exactly the class you seek when you have a predictable, unique file name, with namespaces based on folders, generally.
For naming your files, maybe this:
foo.cs
foo_t.cs
foo_tuv.cs // for a foo class with three generics
I'd recommend keeping the classes in the same file. It makes it easier to locate all Foo classes. Also, with code folding (regions) you can easily view only a single class by collapsing the other.
That said, I wouldn't say either way is wrong. In the end this is one of those things that will take some experience to come up with your personal preference and find what works for you in your particular project. And you may find that what works well for one project doesn't necessarily work for your next project.
Answered here:
I think the common solution to this problem is to name the file like
this:
{ClassName}`{NumberOfGenericParameters}
This would give you this filename:
Bag.cs and Bag`1.cs
This is the way Microsoft handle this issue in frameworks like Asp.net
Mvc.
Keep these classes small and you can keep them in one file. If you can't keep them small, divide them. If you prefer keeping them in separate files, it's okay too. But keep them small anyway. In case of separate file, I would use FooGeneric name but someone here How to name C# source files for generic classes recommends Foo`1 (for 1 parameter).

c# multiple classes in separate files?

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

How to organise large code files?

I am increasingly aware that my code in any single file can often span hundreds of lines quite easily and although I know the implementation might be sound, it still feels messy and unorganised.
I understand that there are situations where a lot of code is neccessary, but whats the best way to organise it all?
I've thought about separating variables from methods, privates from publics and internals but I don't want to because I can't help thinking that the components of ONE class belong in ONE file.
This whole thing is compounded when I'm working with the codebehind of a WPF window, which always seem to grow at an exponential rate into one huge mess very quickly.
Also: C# has a keyword called partial, which allows you to split a class over any number of files without affecting the functionality. However, I have noticed that Microsoft only seem to use partial to hide generated code from you (Winforms / WPF.) Which leads me to question whether splitting a class simply because it has many lines is a legitimate use of partial - is it?
Thanks
Separate your code into responsibilities. For each responsibility, define a single type. That is, follow the Single Responsibility Principal. Doing so will result in smaller units of code, each of which performs a very specific function. Not only does this result in smaller files, but also in better design and maintainability.
If your files are big because they contain a single class/struct that is big, then this is usually (but not always) a hint that your class is dealing with multiple concerns and can be refactored into a number of smaller, more specialised classes.
If I understand you, your main problem is that your forms end up being too big, which leads to the classes for those forms containing too much code, which is quite normal if your forms aren't very simple. The way to try minimize this is by using User Controls since if you move the controls to other classes, you also move the code behind to other classes.
It can sometimes make it a little more difficult to communicate between the controls, but that's usually more than made up for by the fact that the code in each class will be much easier to understand.
I tend to group properties, constructors, methods, and helper methods (private methods) together with regions. If I have a lot of methods, I create more regions based on what they do (especially good for overloads). And speaking of overloads, try minimizing your code with optional parameters.
As far as I understand partial means that the class exists in two separate files. Webforms and controls are partial because the other "part" of the file is the as[p|c]x file that goes with it.
I go on the theory that if you cant see an entire method on one screen (i.e. you have to scroll), you should break the method up into further methods - either in the same class or when the code will get used more than once into a helper class.
We use stylecop. It helps a bit because it enforces a structure on your code and an order for what should appear where. Hence you can then find your way around larger files a bit more intuitively.
To improve code readability: you can use the region block: https://msdn.microsoft.com/en-us/library/9a1ybwek.aspx . As for improving the structure and design of your code - consult some specialist books.

C# classes in separate files? [closed]

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 4 years ago.
Improve this question
Should each class in my C# project get its own file (in your opinion)?
While the one class per file policy is strictly enforced in Java, it's not required by C#. However, it's generally a good idea.
I typically break this rule if I have a very small helper class that is only used by the main class, but I prefer to do that as a nested inner class for clarity's sake.
You can however, split a single class into multiple files using the partial keyword. This is useful for separating your code from wizard-generated code.
Files are cheap, you aren't doing anyone a favor by consolidating many classes into single files.
In Visual Studio, renaming the file in Solution Explorer will rename the class and all references to that class in your project. Even if you rarely use that feature, the cheapness of files and the ease of managing them mean the benefit is infinitely valuable, when divided by its cost.
As others have said, one file per type in general - although where others have made the public/private distinction, I'd just say "one top-level file per type" (so even top-level internal types get their own files).
I have one exception to this, which is less relevant with the advent of the Func and Action delegate types in .NET 3.5: if I'm defining several delegate types in a project, I often bunch them together in a file called Delegates.cs.
There are other very occasional exceptions too - I recently used partial classes to make several autogenerated classes implement the same interface. They already defined the appropriate methods, so it was just a case of writing:
public partial class MessageDescriptor : IDescriptor<MessageDescriptorProto> {}
public partial class FileDescriptor : IDescriptor<FileDescriptorProto> {}
etc. Putting all of those into their own files would have been slightly silly.
One thing to bear in mind with all of this: using ReSharper makes it easier to get to your classes whether they're in sensibly named files or not. That's not to say that organising them properly isn't a good thing anyway; it's more to reinforce the notion that ReSharper rocks :)
I personally believe that every class should be in its own file, this includes nested types as well. About the only exceptions to this rule for me are custom delegates.
Most answers have excluded private classes from this rule but I think those should be in their own file as well. Here is a pattern that I currently use for nested types:
Foo.cs: // Contains only Foo implementation
public partial class Foo
{
// Foo implementation
}
Foo.Bar.cs: // Contains only Foo.Bar implementation
public partial class Foo
{
private class Bar
{
// Bar implementation
}
}
It depends. Most of the time I would say yes, put them in separate files. But if I had a private helper class that would only be used by one other class (like a Linked List's Node or Element) I wouldn't recommend separating them.
As someone who has been coding in large files for years (limited to 1,000 lines), in fact, since I started programming as a child, I was surprised at the huge consensus in this "one class per source file" rule.
The "one class per source file" is not without its problems. If you are working on a lot of things at once, you will have many files open. Sure, you could close files once you're finished with them, but what if you needed to re-open them? There is usually a delay every time I open a file.
I am now going to address points others have made and explain what I think are bad reasons for the "one class per source file" rule. A lot of the problems with multiple classes in one source file are resolved with modern source-editing technology.
"I hate having to scroll up and down" - Bad Reason - Modern IDEs now either have built-in functionality for getting quickly to the code you want or you can install extensions/plugins for that task. Visual Studio's Solution Explorer does this with its search function, but if that's not enough, buy VisualAssist. VisualAssist provides an outline of the items in your source file. No need to scroll, but double-click on what you want.
There is also code-folding. Too much code? Just collapse it into one line! Problem solved.
"Things are easier to find because they're identified by file" - Bad Reason - Again, modern IDEs make it easy to find what you're looking for. Just use Solution Explorer or buy VisualAssist!! The technology is out there, use it!!
"Easier to read/too much code" - Bad Reason - I am not blind. I can see. Again, with code-folding I can easily eliminate the clutter and collapse the code I don't need to see. This is not the Stone Age of programming.
"You will forget where the classes are in large projects" - Bad Reason - Easy solution: Solution Explorer in Visual Studio and the VisualAssist extension.
"You know what's in a project without opening anything" - Good Reason - no dispute with that one.
Source Control/Merging - Good Reason - This is actually one good argument in favour of the "one class per source file" rule, especially in team projects. If multiple people are working on the same project. It allows people to see what has changed, at a glance. I can also see how it can complicate merging processes if you use large, multiple-class files.
Source control and merging processes are really the only compelling reason IMO that the "one class per source file" rule should apply. If I'm working on my own individual projects, no, it's not so important.
They should be in different files, even when it seems like overkill. It's a mistake I still frequently make.
There always comes a time when you you've added enough code to a class that it deserves it's own file. If you decide to create a new file for it at that point then you lose your commit history, which always bites you when you lest want it too.
Public classes: yes
Private classes: (needless to say) no
I actually prefer pretty big .cs files, 5000 lines is pretty reasonable IMO, although most of my files at the moment are only about 500-1000 (In C++, however, I've had some scary files), however, . The Object Browser/Class View, Go to Definition, and incremental search (-I; Thanks for that tip, Jeff Atwood!), all make finding any specific class or method pretty easy.
This is probably all because I am terrible about closing unneded tabs.
This is of course highly dependant on how you work, but there are more than enough tools to not need to use horrible old '70s based file source navigation (Joking, if it wasn't obvious).
Of course! Why wouldn't you? Other than private classes it is silly to have multiple classes in a single file.
I think the one-class-per-file approach makes sense. Certainly for different classes, but especially for base and derived classes, whose interactions and dependencies are often non-obvious and error-prone. Separate files makes it straightforward to view/edit base and derived classes side-by-side and scroll independently.
In the days of printed source code listings running to many hundreds of pages (think of a phone book), the "three finger rule" was good a working limit on complexity: if you needed more than three fingers (or paper clips or post-its) as placeholders to understand a module, that module's dependency set was probably too complex. Given that almost no one uses printed source code listings anymore, I'll suggest that this should be updated as the "three window rule" - if you have to open more than three additional windows to understand code displayed in another window, this code probably should be refactored.
A class hierarchy of more than four levels is a code smell, which is in evidence if you need more than four open windows to see the totality of its behavior. Keeping each class in its own file will improve understandability for depth less than four and will give an indirect warning otherwise.

Categories

Resources