What is the best practice for creating Custom Exceptions? - c#

When creating Custom Exceptions is it best practice to make a separate class file for each and every Custom Exception, or append the Custom Exceptions to the end of the class file that they relate to, or create a file (eg. CustomExceptions.cs) and add the Custom Exceptions there?

One class per file is always a good rule.
The other basics:
Mark your exception as [Serializable]
Overload all the System.Exception constructors
Don't inherit from System.ApplicationException

Well ... I would say that you should follow the rule of one class per file, except in case if this exception is just for "internal" functionality in your class. Then you can make it declared inside the class. However, if exposed by any means to outside world, separate it from the class. This exposure could also be seen from the actual probability that this exception goes unhanded to the users of your class. In this case, I would also expose it and would not declare it inside.

As others have stated, one class per file rule is ideal. Another way to think of it, if you have a large application consisting of many modules, you will have multiple namespaces and it's important to keep the exceptions that a certain class method (or set of classes/methods) can throw within their respective namespaces. This makes the code more readable and the reasoning behind your custom exceptions easier to decipher for other developers ... Or for you in 6 months when you forgot why you made half of them :)

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.

Recommended way to prevent naming pollution by helper classes in 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

Good practice of exception hierarchy in C#

Now I write C# code after the PHP.
In PHP I create a hierarchy of exceptions guided by the recommendations of the Zend Framework(Symfony now use something similar).
In package(for example Order) I create folder Exception, in this folder(translate from php to C#):
namespace Order.Exception
{
interface ExceptionInterface{}
class ApplicationException : System.ApplicationException, ExceptionInterface{}
class OrderNotFoundException : ApplicationException {}
class SomethingHappensException : ApplicationException{}
}
I need a lot of exceptions(relatively) to conveniently express the things from domain.
Is there any have good practices to create hierarchies of exceptions?
Technical details of creation I understand completely. The issue of good practice.
Two quotes from CLR via C#, 4th Edition:
If you want to define an exception type hierarchy, it is highly
recommended that the hierarchy be shallow and wide in order to create
as few base classes as possible. The reason is that base classes act
as a way of treating lots of errors as one error, and this is usually
dangerous.
(...)
There are versioning ramifications here, too. If you define a new
exception type derived from an existing exception type, then all code
that catches the existing base type will now catch your new type as
well. In some scenarios, this may be desired and in some scenarios,
it may not be desired. The problem is that it really depends on how
code that catches the base class responds to the exception type and
types derived from it. Code that never anticipated the new exception
may now behave unpredictably and open security holes. The person
defining the new exception type can’t know about all the places where
the base exception is caught and how it is handled. And so, in
practice, it is impossible to make a good intelligent decision here.

Designing exceptions in a c# application

When designing an application, you have two options how to design the exceptions (imo):
You either create specific exceptions for specific cases and inherit them from System.Exception or some other child System exceptions.
Or you create a base exception for your application which inherits probably from System.Exception, like MyAppException : System.Exception, and then you inherit all of the custom exceptions from that base exception.
I will not ask which approach is better in general because I do not think there is a clear answer. However, I would like to know which approach is more suitable for which applications, e.g. one is better for a winforms application and the other for a class library.
There is no clear answer. No matter the type of application, there are cases where it is better to throw a "generic" application (possibly containing the specific one as an InnerException), and there are cases where it makes sense to inherit from an existing exception.
It's more important to consider who is going to catch the exceptions and what he should be able to do with them.

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