*
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 Android Security Essentials Live Lessons this week in the Android 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: 38062
    
  22
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: 1756
        
        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: 38062
        
      22
    Legibility. I like the static method. I greatly prefer in situ initialisation to static blocks.
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Recommendation for static initialization
     
    Similar Threads
    String Changed
    Need Help with this code
    String and StringBuffer
    String and StringBuffer
    Replace a char in a String