开发者

Are static classes and methods bad? Global variables frowned upon?

I have an application that has database connectivity and although there are obviously objects that correspond to data in my database, I find that all my data processing methods could be static as there is no real need for an instance of the object as my classes simply operate on the data and spit something out, no need to store anything outside the method's scope. If I can make a method or class static should I?

Also I use a utility singleton class for common (single instance) "global data". I want to have a good design, but are these frowned upon?

Let me give you an example of what I'm doing. I load some data from my database using a static method to place it into a global varaiable in my Singleton class (a list of a custom object)

So my singleton class has something like

List<MyCustomObject> SomeList

and my static class has

static void LoadData()
foreach(data in database something or other)
singletonClass.SomeList.Add()

So the code above might load 开发者_如何学Goin some records from the database into SomeList, where each item in SomeList is of type MyCustomObject, which contains a single record of information.

Is this good implementation? Is this how you would code it?

Then in my presentation layer I would make calls to another static class of methods to get data from the singleton class in to a format required.

It doesn't feel very OOPey. But I can't really think how to do it another way you do it.


Allow me to direct you toward an excellent article on this topic: Singletons are Pathological Liars.

The problem is that the need to call your LoadData() function isn't self-evident. Compare your situation to that described in the article and I think you'll see some parallels.


Statics and singletons are frowned upon somewhat. But only the same way as starting a sentence with “but” — bad when overused, but sometimes it's what works best.

In your example, why have separate classes, one a singleton and one static? A singleton is in many ways equivalent to a class with only static data and methods. If you already have a singleton, I'd say you should add the methods to load the data to it rather than to a separate class. A class with static methods would be more appropriate if, say, you have utility code common to all of your stored data types.

(Also, I wouldn't worry too much about what's OOPey and what's not. Overengineering in the blind service of OOP principles can be a serious problem, speaking as someone who's had to wade through the Eclipse code base …)


Singletons is one but static is another very big one.

OOP or not, static variables have many drawbacks but little coding convenience.

  • Can't determine exact allocation time, life span
  • Can't work well in multi-threaded
  • Future problem to program expansion

...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜