Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...