views:

642

answers:

10

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?

A: 

Not entirely. Static actually determines when, where and how often something is instantiated, not who has access to it.

GalacticCowboy
+8  A: 

static doesn't necessarely mean global. Classes and members can be static private, hence only applying to the specific class. That said, having too many public static members instead of using appropriate ways to pass data (method calls, callbacks, etc.) is generally bad design.

inflagranti
`static private` data is still global, though it is only visible to the class in question.
Jeff Sternal
-1 for misunderstanding what private static data is. See above comment.
Timothy Baldridge
I do very well understand what private static means. A private static member is not meant to be accessed globally (i.e. from any other class than the declaring one). Of course its data is global, but without hackery it is not gobally *accessible*.
inflagranti
But it still has the same issues as global data, i.e. Anything accessing that data will be modifying the same piece of data used by every other thread/method call. This is the true issues with global, or static data, it ruins the deterministic nature of the code, and makes it harder to debug, and maintain, since you have no way to know what method modified the code.Static Private data in a C# object is practically different than a file global variable in C. Both have the same drawbacks
Timothy Baldridge
What you are aiming at here is more an issue of parallel data access than of static members. The issues of the same piece of data used by different threads is independant of static or not static data. The problem with public static data is that it is often missused to pass some information between classes/ objects instead of passing the corresponding data as a parameter to a method. Having on static 'registry' introduced some high coupling/dependency on that repository. That's the problem I see with public static, that definitly doesn't apply to private static.
inflagranti
Sorry, I didn't mean to pick a fight about terminology - I just meant that making static variables private doesn't solve **all** of the problems associated with global state. I think of them as "Hidden Globals" [in the term coined by the C2.com contributors](http://www.c2.com/cgi/wiki?GlobalVariablesAreBad).
Jeff Sternal
I totally agree. However, IMO, there is still a considerable difference between private static and public static.
inflagranti
+3  A: 

Mutable static variables are bad because they're just global state. The best discussion I know of about this is here, under the heading "Why Global Variables Should Be Avoided When Unnecessary".

Static methods have several drawbacks that often make them undesirable - the biggest one being that they cannot be used polymorphically.

Jeff Sternal
That depends entirely on your definition of "global".
GalacticCowboy
Any exception for final static variables?
Dean J
@Dean J - indeed, I'm not a madman. :) I'll update my answer accordingly.
Jeff Sternal
+2  A: 

If you're trying to be purist about your OO development, then statics probably don't fit the mold.

However the real world is messier than theory, and statics are often a very useful way to solve some development problems. Use them when appropriate, and in moderation.

Andrew Anderson
+1  A: 

I think the bad thing about global variables is the idea of having global state - variables that can be manipulated anywhere and tend to cause unintended side effects in far-flung areas of a program.

Static data would be similar to global variables in that they introduce a kind of global state. Static methods though are not nearly as bad, assuming they are stateless.

Eric Petroelje
+12  A: 

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.

Timothy Baldridge
+1 for `Global data is bad. However many issues can be avoided by working with static methods.`. That distinguishes static data from static methods.
decyclone
@Tim, without using global data, could you please elaborate how not to waste memory on an IIS server where each request spawns dozens of lookups, maps and dictionaries which could eat up 10-20 MB per connection? I think the blanket statement "global data is bad" will lead web developers to make some poor design choices.
code4life
It appears that no one is really making much use of state versus statelessness, which, imo, is core here. I agree with @code4life on blanket statements being misleading (especially when they're the first sentence!)
Marc
@code4life - you are correct, there are some times when global data is needed. For instance, I have a graphic rendering engine where I cache hundreds of MB for use by multiple threads. So perhaps my blanket statement is a bit off. Let me edit my comment above.
Timothy Baldridge
+2  A: 

As an addition to whatever else is said, final static variables are just fine; constants are a good thing. The only exception to that is when/if you should just move them to a properties file, to be easier to change.

Dean J
This question is tagged as c#, so I'll assume you mean `const` instead of `final static`.
R. Bemrose
The question is also tagged language-agnostic - maybe it's a wash?
Jeff Sternal
Upvote on both comments; I still don't rapidly switch between C# and Java well.
Dean J
+2  A: 

First, why are the old global variables so bad? Because it is state that is accessible from anywhere, any time. Hard to track.

There are no such problems with static methods.

That leaves static fields (variables). If you declared a public static field in a class, that would truly be a global variable and it would be bad.

But make the static field private and most problems are solved. Or better, they are limited to the containing class and that makes them solvable.

Henk Holterman
+1  A: 

Static methods are used to implement traits in Scala. In C#, extension methods (which are static) fulfill that role in part. That could be seen, as the DCI proponents state, as a "higher order form of polymorphism".

Also, static methods can be used to implement functions. This is what F# uses to implement modules. (And also VB.NET.) Functions are useful for (unsurprisingly) functional-programming. And sometimes they're just the way something should be modeled (like the "functions" in the Math class). Again, C# comes close here.

Jordão
+1  A: 
public class Foo
{
    private static int counter = 0;

    public static int getCounterValue()
    {
         return counter;
    }
    //...
    public Foo()
    {
        //other tasks
        counter++;
    }
}

In the code above you can see that we count how many Foo objects were created. This can be useful in many cases.

The static keyword is not global, it's telling you that it's on class level, which can be very useful in various cases. So, in conclusion, class level things are static, object level things are not static.

Lajos Arpad