Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to go for static classes?

Tags:

c#

.net

Whenever I code a solution to something I tend to either use a lot of static classes or none at all. For example in a recent project I had to send a class with some string/bool/datetime data through a number of hoops and the only thing that wasn't static was this data-holding class. Everything else (3 pretty hefty classes with different processing responsibilities) were static.

I think what I'm asking for here is some input on when (and why) I should avoid using static classes for these "process X, output Y" cases. Is it ok to always use them as long as they work or am I shooting myself in the foot concerning scalability, plugin-support etc?

I hope this is an OK question to ask here. I'm not asking for an argument concerning whether or not static classes are "better" - just input on when I should avoid using them.

like image 259
Anders Arpi Avatar asked Dec 21 '22 19:12

Anders Arpi


2 Answers

Most of the code i write:

  • Uses dependency injection/IoC
  • And needs to be mockable/testable

So i just use objects for almost everything.

I do still use statics for things like:

  • Extension methods
  • Constants
  • Helper/Utility methods (pre extension methods)
  • operator methods
like image 136
djeeg Avatar answered Jan 05 '23 00:01

djeeg


Still the two questions remain a bit the same. My main concern on static classes is inheritance and accessability.

When using a static class (public in the worst case), everyone is able to access your processes and functions. Which is most of the time not what you want. It is too easy for some object to get to your functions and do some modifications. Therefore, dependency injection is nice to use. (Pass the object you want to modify in the parameters, which is in this case your process-object).

To prevent others from manipulating your process-object, why not try to use some kind of singleton pattern (or even an ex-singleton pattern), so there is actually a real object to talk to? You can pass the object into the parameters of your functions if something should be modified. And then you can just have one manager that holds your process-object. Others shouldn't get to the object.

Static classes are also hard to inherit. Overriding static methods seems a bit strange. So if you are sure that the process will not be the only process, and some more specific processes will be created by you, then a static class should be avoided as well.

like image 39
Marnix Avatar answered Jan 04 '23 23:01

Marnix