Recommended way to prevent naming pollution by helper classes in C#? - c#

I often come across the pattern that I have a main class and several smaller helper classes or structs.
I'd like to keep the names of thoses structs as clean as possible. So when I have a class that's called CarFinder that heavily makes use of some special Key object that is only (or mainly) used internally, I'd like to call that object Key instead of CarFinderKey.
Everything to remove all the extra fuzz that distracts me from when I try to understand the class while reading it.
Of course I don't want to pollute the rest of the code with a small helper class that is called Key - it most likely will clash and confuse.
In a perfect world I would have liked to have a keyword like internal to this namespace, but as that does not exist that leaves me the following options that I can think of:
Use internal and put the class in a different project.
Advantage: Perfect encapsulation.
Disadvantage: A lot of organisational overhead and unnecessary complicated dependencies.
Note: I'm not talking about really large self contained systems that undoubtedly deserve their own assembly.
Put it in a different child namespace, like CarFinding.Internal
Advantage: Easy to implement.
Disadvantage: Still can pollute when the namespace is accidently imported.
Put the helper class as a child class within CarFinder.
Advantage Doesn't pollute internally and can even be promoted as a public helper struct that is exposed to the outer world with CarFinder.Key
Disadvantage Have to put the helper class within the same file, or encapsulate it in an external file with public partial class around it. The first one makes a file unneccesary long, the second just feels really ugly.
Anyway call it CarFinderKey
Advantage Easy to implement.
Disadvantage Adds in my opinion too much fuzz to CarFinder. Still unncessary pollutes the naming, just with a name that is not likely to clash.
What is the recommended guideline?

Personally, I don't mind the extra "fuzz" caused by CarFinderKey, and here is why: Once worked on a very large project where we tried to use namespaces to disambiguate names.
So as you expand your system, you can very easily end up with 10 tabs open in your code editor, all named "Key.cs". That was seriously not fun.

It's opinion based. Anyway, I would:
try to make it a private nested class of CarFinder, which usually fails because the Key needs to be passed over to CarManager, you know what I mean. Public nested classes are discouraged.
I would put it into a sub-namespace called Core, a common name for internal stuff. For me, Core is "namespace internal" by naming convention.
The larger the project, the longer names you need. CarFinderKey is still a valid option.
I would never create additional assemblies just for this. It just doesn't feel right.

I had the same dilemma many times, and personally use (3) and a variation of (4).
(3): I have no problem with neither putting the nested class/struct within the same file (if it is small and really tied with the parent class), nor using a separate file within partial ParentClass declaration - the only drawback is that it gets one more level of indentation, but I can live with that. I also have no problem with violating FxCop rules or other recommendations - after all, they are just recommendations, not mandatory. But many people do have problems with all or some of these, so let move on.
(4): You already described the cons. What I'm going to share is how I do overcome them. Again, it's personal and one might or might not like it, but here it is.
First, let say we use a separate file for the key class and name the class CarFinderKey.
Then, inside the code file for the CarFinder class, we put the following line at the end of (or anywhere inside) the using section:
using Key = CarFinderKey;
This way, only inside the CarFinder class code file, anywhere CarFinderKey is needed, we can just refer to it simply as Key, what was the goal. At the same time we keep all the advantages and no clashes. Intellisence works w/o any problem. In VS2015, the lightbulb would even suggest to "simplify the name" for you anywhere it finds CarFinderKey inside that file.

Your decision should depend on your design. Is your Key class really a key only for CarFinders, or could it also be used to find motorcycles or houses or whatever.
One of the first rules the famous Gang of Four stipulated was "Design for change". If you really think that in the very near future your key could also be used to find houses or motorcycle, then it would not be a good idea to make your key class thus private that other could not use it.
Since you are speaking about private helper classes, I assume your key is only useful for CarFinders.
If that is the case and your design dictates that the Key is only useful for CarFinders, or maybe even: if it is designed such that it even isn't useful outside CarFinders the Key class ought to be part of the CarFinders class. Compare this to a simple integer that you would use in the CarFinders class, you would declare it private inside the CarFinders class wouldn't you?
Leaves you with the problem of one big file or a partial definition. From design point of view there is no difference. For the compiler there is also no difference. The only difference is for humans who have to read it. If you think that users of your class seldom have to read the definition of your key class, then it is better to define it in a separate file. However, if you regularly need to read the key class while reading the CarFinder class you should make access to the key class as easy as possible. If your development environment is fairly file oriented instead of class oriented, then I think that in that case the disadvantage of a large file is less than the disadvantage of having to switch between files.

I would put the class and their "helpers" in their own namespace MyNamespace.CarFinding,
so that you have :
MyNamespace.CarFinding.CarFinder
MyNamespace.CarFinding.Key
and I will just put this namespace in a sub-folder of the project.
This will not block the internal helper class to be used elsewhere in the project, but from the parent namespace you could reference your helper as CarFinding.Key

Related

C# Can I use partial classes to make code more readable

So for example I have this Web Api controller class AdministratorController and it contains a lot of tasks:
Create
Delete
Edit Password
Update
Get
Get all
Etc...
Now I have all these Tasks in 1 file AdministratorController.cs. But with all comments and annotations the file is pretty long.
Is it a good method to split this controller up into partial class pieces to make developers that search for a specific function get quicker to their destination? Or is this abusing the partial keyword
So for example I have a folder structure of:
--Controllers
⠀|-- Administrators
⠀⠀⠀⠀|-----AdministratorCreateController.cs
⠀⠀⠀⠀|-----AdministratorDeleteController.cs
⠀⠀⠀⠀|-----AdministratorEditPasswordController.cs
Obviously, this is a opinionated answer. Technically speaking, yes you can. It will compile.
I think you are right to split this into multiple files if it gets to long.
You could have partial classes. Or you could just have multiple classes. No one forces you to put all those methods into a single controller.
Personally, I'd opt for the multiple classes for practical reasons. You probably do dependency injection and you probably do it via constructor injection, because this is the default. With partial classes, which just means one big class but multiple files, you now need to edit your current file, plus the file that the constructor resides in to add a new service. It also means all the methods will need the DeleteDataService injected, although only the Delete method uses it. If you had one controller per method, you'd have the constructor in the same file and the other classes are not dependent on it.
But if for example you do injection via [FromService] attribute in your method then there is little difference between your two choices.
Structuring them in different files if keeping them in one file is too long is good. So good, that I don't think it would be too bad, even if you picked the "wrong" method to do it. So pick the one that seems most practical to you.
It depends on what you mean by "readable." To the extent that we must read a class, whatever we have to read doesn't become less by being placed in separate files. There's just as much to read either way. It could even be a nuisance looking through parts of a class across separate files looking for a particular member.
Partial classes might make us feel like we're separating code when we're really just making bigger classes. If we think we're making anything simpler with partial classes then they could even make our code harder to understand by encouraging us to add more to a single class while separating it into different files.
I'm not railing against partial classes. This stuff only exists if there is a use for it, and I don't mean to imply that anyone who uses them is abusing them. One example is autogenerated classes, like when we add a service reference (do we still do that?) We might make some modifications to the class, but then they get lost if we update the service reference and redo the auto-generation. If we put our custom code in a partial class then we can generate part while leaving the rest intact.

Store hierarchical Const data

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.

C#: Un-nested struct in same .cs file as related class?

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.

C# Class function members declaration & implementation

Is there a concept in C# of class definition and implementation similar to what you find in C++?
I prefer to keep my class definitions simple by removing most, if no every, implementations details (it depends on several factors as you may know, but generally I move towards leaving most member implementation details outside the class definition). This has the benefit of giving me a bird's eye view of the class and its functionality.
However in C# it seems I'm forced to define my member functions at the point of declaration. Can this be avoided, or circumvent some way?
During my apprenticeship of C#, this is one aspect that is bothering me. Classes, especially complex ones, become increasingly harder to read.
This is really a case of needing to step back and see the bigger picture. Visual studio has many, many tools to help you write and manipulate your code, from outlining, #regions, class view, class diagrams, the Code Definition Window and many more.
C# isn't C++, if you try to make it so then you'll trip over yourself and no-one else will be able to read your code.
A day spent learning to use the Visual Studio tools will repay the investment many times over in terms of productivity and you'll soon wonder how you ever lived with that C++ way of doing things.
Update in response to comments
I have long since stopped regarding my code as simple text files. I regard code as an organic thing and I find that allowing myself to rely on a feature-rich IDE lets me move up and down levels of abstraction more easily and enhances my productivity no end. I suppose that could be a personal trait and perhaps it is not for everyone; I have a very 'visual' mind and I work best when I can see things in pictures.
That said, a clever IDE is not an excuse for poor style. There are best practices for writing "clean code" that don't require an smart IDE. One of the principles of clean code is to keep the definition of something near its use and I think that could be extended to cover declaration and definition. Personally, I think that separating the declaration and definition makes the code less clear. If you are finding that you get monster classes that are hard to understand, then that might be a sign that you're violating the Single Responsibility Principle.
The reason for separate definition and declaration in c/C++ is because C++ uses a single pass compiler, where forward references cannot be resolved later, unlike C# and its two-pass compiler which can happily find references regardless of the order of declaration. This difference stems from the different design philosphies of the compilers: C/C++ considers each source file to be a unit of compilation, whereas in C# the entire project is considered to be the unit of compilation. I suppose when you are used to working in the C/C++ way then separating the declaration and definition can appear to be a desirable element of style, but I personally believe that keeping declaration and use (or in this case declaration and definition) enhances, rather then reduces, readability. I used to be a C programmer myself until I started using C# in 2001. I always loved C and thought it's way of doing things was the 'bees knees'. These days when I read C/C++ code I think it looks absolutely horrendous and I can't believe we used to put up with working that way. It's all a matter of what you are used to, I suppose.
If you're using Visual Studio, you can take advantage of the Class View. You can also use the expand/collapse features of the source code editor.
In the improbable case that your tools don't help, you can always write a quick utility that will summarize the class for you.
If the class has been compiled, you can use Reflector to view the class, too.
No, there is no concept of implementation and header files in C# like you find in C/C++. The closest you can come to this is to use an interface, but the interface can only define the public members of your class. You would then end up with a 1-to-1 mapping of classes and interfaces, which really isn't the intent for how interfaces are to be used.
You could get a similar result by defining an interface for each of your classes which they then implement.
It sounds like you're referring to interfaces. In c#, you can define all of your member functions in an interface, and then implement them in another class.
In C# you could fake it with partial classes and partial members to a point, however, forward declarations and prototypes go the way of the dodo bird with your newer languages. Class View, Class Diagrams, Intellisense, et al, all help to remove the potential need for those "features".
Define an interface.
Then it's nice to be able to automatically implement the interface using a nice code assist tool.
If you find that a class is hard to read or difficult to understand, that's often a sign that the class is trying to do too much. Instead of trying to duplicate C++'s separation of declarations and definitions, consider refactoring the troublesome class into several classes so that each class has less responsibility.
Whenever it's possible or desirable, I'll go with the previous responses and define an interface. but it's not always appropriate.
alternatively, you can work around this "problem" by using some static code inspection tools. Resharper's "File Structure" window will give you exactly what you want. you can also use the built in "Class View" from visual studio. but I prefer the former.
The prototyping that I guess you are referring to does not really exist in C#. Defining interfaces as others have suggested will give you a point where you have declarations of your methods collected, but it's not the same thing as prototypes, and I am not so sure that it will help you in making your implementation classes easier to read.
C# is not C++, and should probably not be treated as C++.
Not sure what you mean by your classes continue to grow and become hard to read. Do you mean you want a header file like view of a class's members? If so, like John suggested, can't you just collapse the implementation so you don't have to see it?
If you don't want every class to implement a certain thing, then interfaces are probably the way to go (like others are saying).
But as a side thought, if your classes themselves get more and more complex as a your write the program, perhaps it's more of a design issue than a language problem? I think a class should have one responsibility and not take on more and more responsibilities as the program grows, rather the number of classes and how old classes are used should grow and get more complex as you continue to develop your software?
There are two remedies for this to make it more C++-ish:
Create an interface file that declares all method signatures and properties
Implement that interface in a class across multiple files by using the partial modifier on the class definitions
Edits:
// File: ICppLikeInterface.cs
public interface ICppLikeInterface
{
...
}
// File: CppLikeImplementation1.cs
public partial class CppLikeImplementation : ICppLikeInterface
{
...
}
// File: CppLikeImplementation2.cs
public partial class CppLikeImplementation : ICppLikeInterface
{
...
}
The C++ way of separating interface into a header file is mostly (I think) due to an early design decision when C was created to allow fast, incremental compilations during the "old days", as the compiler throws away any meta data, contrary to Smalltalk. This is not a matter with C# (nor Java) where tens of thousands of lines compiles within seconds on recent hardware (C++ still doesn't)

Is it good practise to have multiple class definitions in one file?

Is it good practise to have multiple class definitions in one file? or is it preferable to have one class per file?
I prefer one class per file. You'll never have to search for the correct filename because it is always the class name.
One class per file.
That way you can avoid having to merge edits when two people have to edit the same file because one is working on class A and the other is working on class B. While this should be automatic in any source control system, it's an extra step that can be missed which would cause problems.
Far better to have a process that didn't allow this sort of error to occur in the first place.
I do not see any issue with multiple classes in the same file, as long as the classes are related to each other.
If you have resharper, you can always use the navigation tools to find any class.
It is generally best practice to have one file per class.
Some folk, not me, like to have more than more one if they are related and very very small in size. Others might do this in a prototyping stage. I say start and stay with one per file as does Scott McConnell in his discourse on Class Quality in his seminal book Code Complete
To quote, "Put one class in one file. A file isn't just a bucket that holds some code. If your language allows it, a file should hold a collection of routines that supports one and only one purpose. A file reinforces the idea that a collection of routines are in the same class."
I think it's preferable to have one class per file and to organize them in folders having the same hierarchy as their namespaces.
Most programmers would consider one class per file to be a best practice.
Usually - no.
Following practice "one class per file" simplifies browsing of solution.
Additionally if you have a big team of developers and source control tool that uses pessimistic approach (exclusive locks) - your developers will have hard time while working on the same file.
I guess it is down to preference as you said.
I think you'll find most online examples/ most code is one class per file for easy management.
I sometimes put 2 classes in a file - only if i'm using the second class as an entity and it's only being used in the first class.
I guess you ask because you've noticed already that it's considered best practice. Given the obvious benefits (and some less obvious ones mentioned here), why would you want to do it differently? Are there any benefits at all in multiple classes per file? I can't think of any.
Usually it is the best solution to have one class per file (with the file named exactly like the contained class).
I only differ from that if
There are lots of small enumerations ->I collect these into a single file e.g. Enums.cs
There are lots (20+) of generated classes/interfaces that directly relate to each other ->Into one file E.g. Interfaces.cs
There is stuff that is no direct functional part of the application and in close semantic consistance (e.g. everything you need for interop. Thats usually a few structures, enums, constants and a single class) -> That goes into a single file named after the interop class.
Private inner classes -> Stay with their parent class instead of partial classes
I would say no, i know devexpress hates it aswell ( It has some detection bad practives).
But i do have it sometimes, when its a very small class thats basicly only used by the "main" class in the file. Personaly i think it comes down a bit to taste, there is a balance between having 10k lines long .cs files or having to many .cs in your project.
I think in terms of it being a "best practise" approach then probably yes. However, really it depends on the project. I tend to group related code into separate units for example:
MyApplication.Interfaces
MyApplication.Utils
MyApplication.Controllers
I really think a class only ever deserves it's own unit if it becomes huge. However, if it does get to this stage, you should start to consider moving some code into helper classes to separate the logic.
I would have to agree with most on this. One class per file is ideal. It makes it easier to see what's available in a project without having to rely on intellisense to discover types that are available in a given assembly.
I think the only time I ever fudge on the one class per file rule is when I'm defining a custom EventArgs class and it's related to an event that's fired from another class. Then typically I would define those in along with a delegate for the event in the same file. I don't know that it's a good practice one way or another or just out of sheer lazyness??
If you work on a very large project, too many files can slow down your build times significantly (at least with C++). I don't think that rigid adherence to a rule is necessarily the way to go.
One Class Per File is my Preferred approach, it helps me get rid of any confusion later on... I tend to use a lot of partial classes though...
As long as I dont break the 1000 line barrier, I'll stuff in as many related classes that makes sense.
Sometimes an abstraction may only be one overridden method.

Categories