This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes Recommendation for static initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Recommendation for static initialization" Watch "Recommendation for static initialization" New topic
Author

Recommendation for static initialization

Rajdeep Biswas
Ranch Hand

Joined: Mar 26, 2012
Posts: 186

Hello,
I have seen people recommend the second practice against the first in context of writing the static initialization of variables:

Method 1:


Method 2:

Which method is recommended and why?

Thanks and regards,
xploreraj


The biggest gamble will be to ask a question whose answer you know in that it will challenge your theory | www.TechAspire.blogspot.in
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38474
    
  23
Neither. Both are dangerous bits of code because you have public non‑final fields. You are using global variables, which can be error‑prone because the class has no control over those values.

I suggest:-
  • 1: You can use a static initialiser.
  • 2: You can initialise in situ.
  • 3: Both have the same effect. Use whichever you think is easier to read.
  • 4: You sometimes need a static initialiser, as code below.
  • 5: I suggest you use only one initialiser, because you can get confused about execution order.
  • Jelle Klap
    Bartender

    Joined: Mar 10, 2008
    Posts: 1761
        
        7

    Another option would be to use a private static method call to, for instance, initialize a collection reference to an instance that contains default/fixed elements. I usually prefer that to a static initilization block.


    Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
    Rajdeep Biswas
    Ranch Hand

    Joined: Mar 26, 2012
    Posts: 186

    Alright. You mean both of them have no conclusive differences.
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 38474
        
      23
    Legibility. I like the static method. I greatly prefer in situ initialisation to static blocks.
     
    jQuery in Action, 2nd edition
     
    subject: Recommendation for static initialization