So I was wondering today, where would you put utility classes in an ASP.NET MVC app? By utility classes I mean classes that can be static and are just used to perform a function. Like a class to send an email that takes email address , subject, and body as arguments.
I would assume maybe creating a separate folder and namespace would be good enough, but wanted to get everyone opinions
|
|||||||||||||||||||||
|
You don't. And your own example is a perfect one to show why not. You want to send emails, right? So you create somewhere a static class Now, what happens if you want to unit-test your class? You can't, because every time you want to test the method which resets the password, it changes the database (which is not suitable for a unit test), and moreover sends an email (which is even worse). You may have read about Inversion of Control, which has a benefit of making unit testing easier. Articles about IoC will explain you that instead of doing something like:
you do:
which allows to use mocks and stubs. Try to apply IoC to your |
|||||||||
|
The question is a valid one, even if the example given is not. The answer given by Maina is perfect, in a very specific context, which is not, to me, the proper context for said "utility" classes. Personnaly, I create a folder "Helpers" in which I put simple functions to be called from about anywhere, like extensions, in which case, yes, they are static. Now, if there is a better way, I will be glad to learn, but so far: -I see nothing wrong with Extensions. -I see nothing wrong with grouping them in a specific Folder. Now, an extension is just syntaxic sugar, it could as well be a classic function. |
|||
|
Don't create static classes for utilities. Statics are bad in most cases. Don't call them managers either. Whatever it is you are working on, it should be placed in a logical namespace. For example:
Email address, subject and body is a separate concern, therefore I would have a class structure for that, hence why I've used |
|||
|