In this episode, we look at how to use static attributes and methods in our class design. These are important but can be over-used. They can even be a supported way to break the object-oriented nature of our program. We can “static” our way into a design that can not be extended. Therefore, we need to use these sparingly and with consideration about how they may limit our solution.
It always helps to set the stage for these types of discussions. Static attributes and methods are not supported by all languages, nor is that always the proper terminology. For our purposes, a “static” is a class level value or function. Thus, there is only one version of these items. There is not a version on each instance.For example, a class-level attribute of “counter” will have the same value for all instances. When the counter variable is altered, all instances see that new value. As you can see, this approach will tie our instances together in a loose way. They are now linked through the static properties.
The software pattern “singleton” is an example where static values and methods are useful. They are almost required to implement this pattern properly. In this case, we have a single instance only for a class. This could be to provide global values or to limit access to resources. We might even blur the singleton into a limited number of instances. This option is a great way to have a small number of files open or database connections.
A Static Anti-Pattern
One of the uses of a static value is as a way to pass around or share that value. This approach can be used to avoid method parameters or a data store. While that is a valid way approach, it can be limiting and error-prone. A static value opens us up to the idea of race conditions. What happens when two bits of code try to update the value at the same time? It will be cleaner for us to pass values and limit access through properly designed methods, even though the direct approach is likely going to require less code.
This feature provides us a lot of power. However, with great power comes great responsibility. Design responsibly.