When to use static variables?

I am currently doing a project in C # with a lot of rendering, and for almost all classes there is a constant value of the integer type used to scale the rendering. I know that I can define this constant in one place as an ordinary variable, and then pass it, but it seems very cumbersome. When is it permissible to use static variables in C #? The easiest solution to my problem is to create a class containing a static variable that all other classes can refer to - will this be a bad design?

+3
source share
5 answers

Nice design in general. In fact, having a Common or Utility namespace and class that provides static methods and static values ​​centralizes these values ​​in one place, so you can guarantee that every module in your application uses the appropriate values. It is low cohesion, but acceptable for profit. I do not see a problem with this.

+7
source

How constant is the value? static great for readonly things, but you can quickly get into a mess if it is not readonly - especially if you have multiple threads. The scaling factor for me is not like a solid constant - i.e. Is not:

 public const double ScaleFactor = 1; 

I would not hesitate to use a static variable for what I load once and leave alone. Besides that, I would apparently encapsulate (in your case) some RenderContext with this value and any other utility methods - and pass the RenderContext between the methods; it can also help you ignore the base implementation if you need unit test, etc.

It seems to you that you need more properties (and you will inevitably be), you just extend the RenderContext class - nothing else changes.


(edit)

Also - think about the future: will you ever do more than one render? Since we all have many cores, etc .... static is good if all threads share a value. There is [ThreadStatic] , but this comparison is a little useless.

+8
source

No, that would be an ideal candidate for static variables. You can even take one more step and make the class static so that it cannot be created. Then you can add all your constants to this class, as well as some helper methods.

+6
source

Answer: if the program works and is supported, do it.

Static variables are not a sin, it’s just useful to know when to use them. :)

+2
source

If all your classes need to understand this value + do something else, then (if it doesn't look like pi), you should probably check that your classes have one problem. Is it possible that “value” should become an object that can perform operations that are currently being performed throughout your code base?

+1
source

All Articles