0

Is there any alternative to static initializers in Java?

Just a random example:

private static List<String> list;

static {
    list = new ArrayList<>();
    list.add("foo")
}

Doesn't it make debugging harder?

Mahozad
  • 18,032
  • 13
  • 118
  • 133
  • Especially if that code throws an exception. There is no one size answer here – Ruan Mendes Jun 26 '18 at 20:02
  • 3
    Kinda depends on what you're trying to accomplish. If you can create an instance of the class, you can usually get away with doing this in a constructor. If you're using dependency injection/inversion of control, you'd rely on your DI layer to inject a list for your class with a specified value for you. **You need to add more details** to this question so we can understand the context you're in. – Makoto Jun 26 '18 at 20:06
  • You can also make a private static method that does the initialization (and can trap an Exception and report it). So `static List list = initList();` and then `private static List initList() { ... }`. Such an approach allows for setting a break point and/or logging in the private static method. – KevinO Jun 26 '18 at 20:08
  • Why would debugging be harder? --- *"Is there any alternative?"* Singleton. – Andreas Jun 26 '18 at 20:10
  • @KevinO You can set breakpoint and do logging in a static initializer too, so that's no argument for anything. – Andreas Jun 26 '18 at 20:13
  • @Makoto it's a general question (if such questions are acceptable!) and the code I provided is a random example I remembered. – Mahozad Jun 26 '18 at 20:17
  • @Mahozad: It becomes a bit too broad if you make it *too* general. Narrow it down and make it easier for us to tackle. – Makoto Jun 26 '18 at 20:21
  • My question is broad because static initializers seem ugly to me – Mahozad Jun 26 '18 at 20:27
  • @Mahozad then don't use them if you find them ugly. – Lino Jun 26 '18 at 20:28
  • @Lino Well what is the alternative way?! – Mahozad Jun 26 '18 at 20:36
  • @Mahozad look at the answer from Mureinik – Lino Jun 26 '18 at 20:37

1 Answers1

4

If you need a static list you will need to initialize it **somewhere*. A static initializer is a fair choice, although in this example, you can trim it down to a one liner:

private static List<String> list = new ArrayList<>(Arrays.asList("foo"));

Or, if this list shouldn't be modified during the program's lifetime, ever shorter:

private static final List<String> list = Collections.singletonList("foo");

Or as noted in the comment, in Java 9 and above:

private static final List<String> list = List.of("foo");
Mureinik
  • 297,002
  • 52
  • 306
  • 350