2

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() {...}
}
Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
sudo
  • 329
  • 7
  • 14
  • 6
    Short answer: it doesn't matter. Longer answer: it *really* doesn't matter. Readability, reliability, and maintainability are the goals, not micro-optimizations. Also, Java doesn't have global variables. Your example illustrates instance variables. If you still want to know, set up a test and time it. – Jonathon Faust Nov 19 '10 at 04:23
  • +1 for "test it", Jonathon. It's tiresome to read and re-read people asking questions that could have been definitively answered with about ten minutes' work. – JUST MY correct OPINION Nov 19 '10 at 04:28

3 Answers3

12
  • 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.

Community
  • 1
  • 1
Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
  • 1
    I disagree with your last bullet there - classes are globally scoped, and thus all class variables are globally scoped. – gustafc Nov 19 '10 at 09:20
  • @gustafc: BTW, a class variable is not a global variable, arguably. Well you can try to look at it in this way that it is a way we try to avoid any confusion. In some languages, the term "static variable" is generally not used, since "local" and "global" suffice to cover all the possibilities. But in Java its not the case, so we avoid it altogether. – Adeel Ansari Nov 19 '10 at 09:30
  • @gustafc: Global means, at least to some folks coming from different languages, a variable which is also outside of any class, hence global is a real sense. I hope you are getting my point. You can try searching "global variables in Java", you will definitely come across results which are suggesting the same. – Adeel Ansari Nov 19 '10 at 09:38
  • @Adeel Ansari, first hit on "global variables in Java" is [this](http://www.glenmccl.com/tip_002.htm) ;) But that's beside the point, just because you've got good Google ranking doesn't mean you're right. I'd argue that "global variable" means "globally scoped variable", and whether or not the variable is declared inside a Java class, a C++ namespace, a Python module, etc is irrelevant. The only good argument against class variables being global is that they're actually local to the classloader that loaded the class, but that's a very technical issue and irrelevant to most everyday use cases. – gustafc Nov 19 '10 at 11:06
  • @gustafc: Of course it's not about the Google ranking. But my point is we normally don't refer class variables as global variables, because it tends to confuse folks coming from different background. Likewise, in the start we used the notion of objects are pass-by-reference, but that tend to confuse concepts. So, now we completely changed that and instead say, that references are pass-by-value. I hope this time, you are getting from where I am coming from. – Adeel Ansari Nov 19 '10 at 12:58
  • @Adeel, who are those "we" you speak of? Anyway, I'd say it's more confusing claiming there are no global variables in Java, when in fact there are. – gustafc Nov 21 '10 at 11:01
  • @gustafc: The folks agreed with me here, and those who have given similar answer to the similar question in the link provided, and those who have upvoted those answers. If you can show me a variable in Java which doesn't really belong to any class, I will start saying with you that there are global variables in Java. Otherwise, I would say that a variable in Java is always locally scoped, either in class, object, or method. – Adeel Ansari Nov 21 '10 at 15:31
  • @gustafc: Furthermore, please read the comment by `Jonathan` to the original question here. I can't help it anymore if you have already decided to not understanding whatsoever. :) – Adeel Ansari Nov 21 '10 at 15:34
  • @Aneel, I understand perfectly well what you mean, it's just that you (and Jonathan) are wrong. They phrase it well on Wikipedia (despite the silly passage later in the article where they say that Java doesn't have globals): *a global variable is a variable that is accessible in every scope (unless shadowed)*. Sounds like a public static to me. – gustafc Nov 21 '10 at 19:08
  • @gustafc: Hey its not just me and Jonathan, it seems like whole programming world is wrong. I added few more links for you as evidence, in a hope that you might try to save them too. Thanks. – Adeel Ansari Nov 22 '10 at 02:58
  • 1
    @gustafc - do you know what you get in Java when you create a new classloader (as a child of the bootstrap classloader) and load a class that you've already loaded? Answer: new copy of the class ... complete with its own new set of statics. Very UN-global. – Stephen C Apr 21 '11 at 05:16
  • @Stephen: Excellent point, pal. I am bringing it to the original post. – Adeel Ansari Apr 21 '11 at 05:19
  • dont use static variables to mimic global variables - sooner or later you get nullpointerExceptions - if the class is unloaded. There is no way you can avoid this 100% and if you sell your app it will happen sooner or later.... – user387184 Nov 05 '11 at 19:53
  • C# may not technically have global variables, but some people (probably with background in procedural languages) tend to sort of emulate global variables via so-called God-objects - enormously big classes exposing dozens and dozens of variables. – Konrad Morawski Mar 06 '12 at 08:23
  • 1
    @StephenC - on the other hand, if you make a "global variables class" and all classes using it are loaded by either the same class loader or a child of it - you have decidedly *global* variables. (Many apps use system properties for this purpose, I'm sorry to say. They're really quite lovely for this purpose - not only are they global, they're also not typesafe.) – gustafc Oct 01 '12 at 19:53
  • @StephenC This seems to imply that "the boot class loader" is a global value .... – Ingo Mar 13 '13 at 11:05
  • @Ingo: We're talking about global variables, not global classes, ClassLoader is a class. Btw, I have never heard the term global classes. – Adeel Ansari Mar 14 '13 at 01:45
  • @AdeelAnsari The boot class loader is surely an instance of class ClassLoader, not a class. – Ingo Mar 14 '13 at 08:35
  • It is nonsense to say there are no global variables in Java. It is playing with words. Public static serve exactly the same purpose in the same way public static final are global constants. Also the premature optimization is the source of all evil is another bandied myth : in the same article Knuth lectured on the importance of thinking about efficiency at an early stage. – RichieHH Mar 12 '16 at 12:57
0

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.

bwawok
  • 14,898
  • 7
  • 32
  • 43
  • 2
    I think it's rather silly to say "performance doesn't matter" without qualification. Yes *most* micro-optimizations are probably not worth the effort, but every now and then they are. It's useful to know the difference between the two cases rather than just saying it doesn't matter. – Michael McGowan Nov 19 '10 at 04:41
0

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.

luis.espinal
  • 10,331
  • 6
  • 39
  • 55