Static Methods or Not? Global variables?

2019-08-12 03:40发布

I want to know what way is more efficient.

  1. No global variables, passing variables through parameters, having all methods static

  2. No global variables, having only main method static and creating class object in main to access methods

  3. Use only global variables, having only main method static and creating class object in main to access methods

I am currently using method 3 but I want to know what is more efficient. This class will not be used by any other class outside of it, it pretty much stands alone.

Example of my code structure:

public class myClass {
   private int globalVariable;

   public static void main(String args[]) {
      myClass c;
      c.someMethod(); // Changes global variable from method
      System.out.println(someMethod); // Prints solution
   }

   public void someMethod() {...}
}

标签: java oop static
3条回答
男人必须洒脱
2楼-- · 2019-08-12 04:28

Performance doesn't matter. You want it as easy to read as possible.

I would do 2 as much as you can. When you really need constants and statics, make constants and statics.

For example, a null safe trim makes a good static method. New upping a StringTrimmer is silly. Putting if null then x else z in 1000 others is silly.

查看更多
倾城 Initia
3楼-- · 2019-08-12 04:32

I think this was settled back in 1956 and 1958, when people invented Lisp and ALGOL58 and pondered about modularity, referential transparency, and sound code structure as means to tackle impenetrable spaghetti code that rely on global variables (and who tend to exhibit the software equivalent of the Heisenberg uncertainty principle.)

I mean seriously, this is 2011 and we still wonder about whether to use global variables over encapsulated fields or parameter passing for quote-n-quote efficiency. I mean, seriously.

I may sound arrogant (so be it), but I'll say this:

I can understand some spaces where you have to make some sort of global variable trade-offs (.ie. very resource constrained embedded platforms, for example). I can understand if a person that is just starting in CS (say a freshman) asks this.

But if someone beyond freshman level (let alone someone that does coding for a living and not coding in the most resource barren of environments) asks or even remotely thinks about this as an acceptable thing to do should seriously reconsider going back to the basics (or reconsider this profession - we have too much craptacular code already.)

Short and concise answer: No, it makes no sense. There are no noticeable games. It is not worth it. It leads to craptacular code. And all of these have been known for 50 years now.

查看更多
我命由我不由天
4楼-- · 2019-08-12 04:33
  • No class is an island.
  • There are no silver-bullets, at least its very true in programming.
  • Premature optimisation is the root of all evil.
  • In Java we don't have global variables. We only have class variables, instance variables, and method variables.

[Edit]

I am trying to explain here my last point. In fact, bringing the discussion, that is going-on in comments below, to the actual post.

First look at this, an SO thread of C#. There folks are also suggesting the same thing, which is,

So, here we go.

retort: Classes are globally scoped, and thus all class variables are globally scoped. Hence should be called global.

counter-retort: Not all classes are globally scoped. A class can be package-private. Therefore, the static variables in there will not be visible outside the package. Hence, should not be called as global. Furthermore, classes can be nested, thus can be private as well and definitely can have some static variables but those wouldn't be called global.

retort: public classes are globally scoped, and thus all class variables are globally scoped.

counter-retort: Not exactly. I would like to move the previous argument here but on a variable level. No matter if the class itself is public. The variables in there can be protected, package-private and private. Hence, static variables will not be global in that case.

Now, if you like to call public static variable in public static class, as global then call it by any means. But consider this, when you create a new ClassLoader (as a child of the bootstrap ClassLoader) and load a class that you've already loaded. Then that results in a "very new copy of the class" -- complete with its own new set of statics. Very "un-global", indeed. However, we don't use the word global in Java because it tends to confuse the things and then we need to come with whole lot of explanations just to make everything clear. Folks rightly like to explain the feature of global variables in Java by static variables. There is no problem in that. If you have some problem/code in any other language and that is using global variables and you need to convert that code to Java, then you most likely make use of static variable as an alternative.

A couple of examples I like to render here

  1. When I started Java, instructors like to explain the difference of passing object type variable and primitive variables. And they constantly use the term objects are pass-by-reference, whereas primitives are pass-by-value. Students found this explanation quite confusing. So, we came up with the notion that everything in Java is pass-by-value. And we explain that for objects references are pass-by-value. It becomes much more clear and simple.

  2. Similarly, there are languages which support multiple-inheritance. But Java doesn't, again arguably speaking. But folks tend to explain that feature using interfaces. They explain it by class implementing many interfaces, and call it multiple-inheritance. That's perfectly fine. But what the class, actually, receives by inheriting a number of interfaces. Frankly speaking, nothing. Why?

    . Because all the variables in interfaces are implicitly public, final and static, which apparently means those belongs to the class and anyone can access those. Now we can say that perhaps there would be some inner class in the interface, then the class implementing the interface will have it. But again that will be static implicitly and will belong to the interface. Therefore, all what the class will get are methods. And don't forget just the definition and the contract which says, "the class implementing this interface must provide the implementation of all methods or declare itself abstract". Hence, that class will only get responsibilities and nothing much. But that solves our problems in a brilliant way.

Bottom line

Therefore, we say

  • There are no global variables in Java
  • Java doesn't support multiple-inheritance, but something like that can be achieved by implementing multiple interfaces. And that really works
  • There is nothing pass-by-reference in Java, but references are pass-by-value

Now I like to site few more places

  • Java does not support global, universally accessible variables. You can get the same sorts of effects with classes that have static variables [Ref]
  • However, extern in ObjectiveC is not an alternative to a class-scoped static variable in Java, in fact it is more like a global variable … so use with caution. [Ref]
  • In place of global variables as in C/C++, Java allows variables in a class to be declared static [Ref]
  • Furthermore, the overuse of static members can lead to problems similar to those experienced in languages like C and C++ that support global variables and global functions. [Ref]

All these are inferring one and the same idea. Which is Java doesn't support global variables.

Hell, I wrote that much. Sorry folks.

查看更多
登录 后发表回答