Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Recommendation for static initialization

 
Rajdeep Biswas
Ranch Hand
Posts: 187
Eclipse IDE Java Opera
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Campbell Ritchie
Sheriff
Pie
Posts: 47232
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
    Posts: 1951
    7
    Eclipse IDE Java
    • 0
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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.
     
    Rajdeep Biswas
    Ranch Hand
    Posts: 187
    Eclipse IDE Java Opera
    • 0
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Alright. You mean both of them have no conclusive differences.
     
    Campbell Ritchie
    Sheriff
    Pie
    Posts: 47232
    52
    • 0
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Legibility. I like the static method. I greatly prefer in situ initialisation to static blocks.
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic