Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are global static classes and methods bad?

It's generally agreed upon that relying heavily on global stuff is to be avoided. Wouldn't using static classes and methods be the same thing?

like image 226
Adam Kane Avatar asked Jun 30 '10 17:06

Adam Kane


1 Answers

Global data is bad. However many issues can be avoided by working with static methods.

I'm going to take the position of Rich Hickey on this one and explain it like this:

To build the most reliable systems in C# use static methods and classes, but not global data. For instance if you hand in a data object into a static method, and that static method does not access any static data, then you can be assured that given that input data the output of the function will always be the same. This is the position taken by Erlang, Lisp, Clojure, and every other Functional Programming language.

Using static methods can greatly simplify multi-threaded coding, since, if programmed correctly, only one thread will have access to a given set of data at a time. And that is really what it comes down to. Having global data is bad since it is a state that can be changed by who knows what thread, and any time. Static methods however allow for very clean code that can be tested in smaller increments.

I know this will be hotly debated, as it flies in the face of C#'s OOP thought process, but I have found that the more static methods I use, the cleaner and more reliable my code is.

This video explains it better than I can, but shows how immutable data, and static methods can produce some extremely thread-safe code.


Let me clarify a bit more some issues with Global Data. Constant (or read-only) global data isn't nearly as big of an issue as mutable (read/write) global data. Therefore if it makes sense to have a global cache of data, use global data! To some extent every application that uses a database will have that, since we could say that all a SQL Database is one massive global variable that holds data.

So making a blanket statement like I did above is probably a bit strong. Instead, let's say that having global data introduces many issues that can be avoid by having local data instead.

Some languages such as Erlang get around this issue by having the cache in a separate thread that handles all requests for that data. This way you know that all requests and modifications to that data will be atomic and the global cache will not be left in some unknown state.

like image 130
Timothy Baldridge Avatar answered Oct 05 '22 21:10

Timothy Baldridge