Currently I'm using logger in my project in the following way :
private static final Logger LOGGER;
static{
LOGGER = logger.getLogger();
}
I got a code review for using static block to initialize the logger variable. I was told to intialize the logger variable in the declaration statement itself.
private static final Logger LOGGER = Logger.getLogger();
I'm trying to figure out as to what difference will it make if I don't initialize it in the static block. I want to know if this is a practice.
-
8It doesn't make any difference, but one of them involves more typing and more lines of code.Stack Exchange Broke The Law– Stack Exchange Broke The Law2017年07月03日 22:46:54 +00:00Commented Jul 3, 2017 at 22:46
-
They will both generate exactly the same bytecode. Which one you prefer is entirely a matter of taste,user207421– user2074212017年07月04日 03:05:14 +00:00Commented Jul 4, 2017 at 3:05
-
Why don't you use Lombok?Martin Schröder– Martin Schröder2017年07月10日 08:22:10 +00:00Commented Jul 10, 2017 at 8:22
-
Lombok is cancerDavid DeMar– David DeMar2025年03月08日 15:29:07 +00:00Commented Mar 8 at 15:29
1 Answer 1
Except for some really bizarre corner cases involving the sequence of initializers, the two alternatives will work exactly the same.
However, initializing the instance right in the declaration is shorter and more familiar, and should be preferred for that reason alone.
Static initialization blocks are a somewhat exotic construct and should only be used when they actually provide added value, such as when you need to handle exceptions.
-
7Good point mentioning Exceptions as a rare case for using static blocks.user949300– user9493002017年07月03日 16:24:49 +00:00Commented Jul 3, 2017 at 16:24
-
4Intializing a HashMap is another good usecase.RubberDuck– RubberDuck2017年07月03日 21:34:34 +00:00Commented Jul 3, 2017 at 21:34
-
3@RubberDuck Although Java 9's
Map.of
methods should help with that.cbojar– cbojar2017年07月03日 23:18:38 +00:00Commented Jul 3, 2017 at 23:18 -
1@cbojar
Map.of
returns an immutable map though, so if you actually need aHashMap
you still need to do it the old way. Or something likenew HashMap(Map.of(...))
kapex– kapex2017年07月04日 08:32:30 +00:00Commented Jul 4, 2017 at 8:32 -
1@Kapep Yes, using it to pass to the constructor is how I would do it if I needed a mutable map instead of the initializer block.cbojar– cbojar2017年07月04日 13:39:17 +00:00Commented Jul 4, 2017 at 13:39