Static Classes
Hi, all! I would like to know what the purpose of creating a static class is, and when I declare a class as static, what exactly happens?
I know that when I have a static variable, it becomes constant throughout all scripts utilizing it. This wouldn't make sense for a class though.
Also, what is the purpose of static functions and what are the implications of doing so?
My best understanding so far is that using static on functions and classes, I can have a script titled 'functions' that are generic functions that I can call from any script. And I can have a folder called 'Monobehaviours' or something that contain just classes that I might need to use a lot.
If you're too lazy to read:
What happens to a class when you declare it as static?
What is the general use of static classes?
When is it important to use them?
Warnings / tips?
Same goes for static functions.
Thanks! - YA
There is an article on that and other thing here : http://unitygems.com/memorymanagement/
Heads-up: static data inside a static class (as well as anywhere) is not serialized!
That's not really something new. This applies to pretty much any program$$anonymous$$g language and almost any serialization system. So please do not wake up years old questions to add this information.
Answer by $$anonymous$$ · Dec 01, 2012 at 10:45 PM
Generally the point of object-oriented programming is to remove global data from the source code. When you work with the pure procedural paradigm of programming (only functions and data with no objects), you have the problem that data is generally not very well encapsulated. It is public to most of the program, and functions are free to manipulate them as they please, which can of course become dangerous and can be prone to bugs.
In the object-oriented paradigm there generally is no such thing as "global data". Everything is stuck inside classes in one way or another. The closest thing you get to global data is things such as static variables.
First of all, a static variable which is part of a non-static class is still associated with that class. The only difference is that instead of each instance of the class having a unique copy of it, all instances share the same memory for that variable, thus it is the same variable they share as you already stated.
When you declare a static class, the only thing you do is actually telling the compiler that no members (data and functions members) can be declared as anything other than static. I think that's what might confuse you. A static class is really the same as any other class, the only difference the static keyword does is tell the compiler that only static variables and methods can go in it, and throws you an error if you try to do it. Also, you are not allowed to instantiate a static class!
When it comes to the design issues on static classes there is a whole lot of different opinions as to when or even if you should use them (same goes for the singleton pattern, which is generally frowned upon).
The thing is that static classes goes against the object-oriented paradigm in that you declare data as global. Any part of your program can access it. And this is the reason as why you have to be careful about using them, since it is easy to introduce bugs. For example, if you have a static variable in a class which defines something like how long the program have been running (just an example here), it is easy for other client code to go in a manipulate it in such a way that it becomes incorrect during the programs lifetime, furthermore it's hard to debug from where the change is actually coming from. So that's one thing to be careful of.
Another thing is obviously when you start working with multi-threading and have to make sure threads don't introduce race-conditions and such to the static data...
I would say that right now, use static classes if you feel the need for it. Just be aware of the design implications it can have on your program. Depending on your situation it might be a good idea to use it, like if you have things in your game which is only declared once and should be used by a lot of other code to do calculations. In a game I'm working on, I have static data such as a "cube dimension" which defines the width, height and depth of cubes which the game is made out of, and it's used in many scripts to make calculations that's depending on that data.
Other good ways to use a static class would be to library functions that simply take some input and gives you some output. You can look at classes such as the "mathf" library in Unity, which is a static class that provides you with a lot of helper functions for mathematical calculations. This kind of class does not save any data for you, it simply provides you with ways to calculate input.
Wall of text here :D But hope you can use some of the information :)
This makes a lot of sense, and I have now realized that this is not the way to go for my project. Thank you very much for your time! This is an awesome answer and I hope that it gets upvoted enough for people to see it. Thanks!- YA
No problem! Glad I could help :) It is great that you stop up to think twice about the implications of using something before doing it, keep that attitude up! Also, if you want to I would recommend searching the web for design issues linked with static classes. There's a lot of good information on it. Also, as you progress more into the world of object-oriented program$$anonymous$$g you will likely see a whole lot of different opinions on what approaches are good and bad. The thing is, I try to keep it as practical as possible without making it too theoretical, since you easily come to a point where your productivity simply stops due to too many abstract and theoretical considerations. Program, learn the flaws if what you are doing, and remember them for future projects :)
Just like to add some details:
Basically, in regard to the question, you're right. The main purpose of a static class is to restrict all of it's members (variables / methods / properties) to be static as well. Furthermore a static class is a requirement for extension methods. They can only be declared in a static class.
However saying "static" is bad is just wrong ;) When you say static variables are bad then yes. Static variables represents a global state which can cause many problems (which you haven't mentioned).
Static methods are not bad at all. They are even slightly "better" than instance methods. When you write a function which don't belongs to a certain class, make it static.
Your concerns were mainly about encapsulation which is also possible with static functions / properties / variables. If a variable is static you can't access it from outside so the static class is the only one who can change it. Everything is encapsulated as it should be. Only expose what others really need. What you expose you have to expect that someone will change it. That's the point of "public".
Static variables have another problem. A class should be designed to perform a very specific task. Usually when you provide the same input to a system / class / ... you would expect the exact same output. A class instance represents one state which is initialized when the class is created. Static variables represents a global state which can't be predicted.
A simple example is Random.Range. It is a static function which uses a private static variable. So the function encapsulates a global state which you can't see and can't influence (well you can indirectly influence it by setting a seed). This becomes a real problem when it comes to multithreading. A thread can change the global state and another one is affected by the state without any notice.
That's way the class System.Random is a real class without global state. It also encapsulates it's internal counter variables, but the state is stored in the instance of the class. You can create 10 instances and each has it's own state. Each instance will behave exactly the same.
There are of course always some global states which can't be avoided at first glance. The most popular is the system time. It is a state and for this pc global. Anyway it should be avoided to use the system time directly in a class. It's better to have a Time class which is passed to your class. This way you can simulate a certain time.
Anyway, it's actually impossible to program 100% OOP conform. Unity is designed for being user friendly and easy to use. $$anonymous$$ost global states in Unity are obvious so we, the users, can take them into account. It's all about the abillity to predict what the system is doing. We write programs to get a certain result, program$$anonymous$$g is not gambling ;)
So now we have two walls of text. If someone writes a "roof" we almost have a house ;)
Answer by Nemox · Dec 01, 2012 at 10:35 PM
It's been a long time since I last used statics, but I'll try to answer as best as I remember.
A static class is essentially a library of data or functions you want performed, but you don't want an actual object of that type to exist. Example, you may have a Gameplay class that gives you some calculations and such, but you wouldn't want a Gameplay object.
Answer by Owen-Reynolds · Dec 02, 2012 at 03:43 AM
To follow up on Nemox's response, all static functions is a way to write "normal" functions in a fake namespace:
class utility {
static closeEnough(float a, float b) { return (a>=b-SMALL && a<=b+SMALL); }
const float SMALL = 0.1f;
static sqrd(float a) { return a*a; }
...
You can then, without having to attach the script on a scene object, use `utility.closeEnough(cats, dogs)` and `utility.sqrd(D)`.
Your answer
Follow this Question
Related Questions
How to call a method from a class in a different script in c# 1 Answer
Setting public static variables in a static class 2 Answers
Best way to communicate between scripts 4 Answers
Can Static classes have static lists? 1 Answer
I cant access a script that I made in Assets/Scripts from the FirstPersonCharacter script. 1 Answer