Can someone explain me what the following is?
public class Stuff
{
static
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch ( ClassNotFoundException exception )
{
log.error( "ClassNotFoundException " + exception.getMessage( ) );
}
...
}
What does this static { ...} do?
I know about static variables from C++, but is that a static block or something?
When is this stuff going to get executed?
The static block is called a class static initializer - it gets run the first time the class is loaded (and it's the only time it's run [footnote]).
The purpose of that particular block is to check if the MySQL driver is on the classpath (and throw/log error if it's not).
[footnote] The static block run once per classloader that loads the class (so if you had multiple class loaders that are distinct from each other (e.g. doesn't delegate for example), it will be executed once each.
The primary use of static initializers blocks are to do various bits of initialization that may not be appropriate inside a constructor such that taken together the constructor and initializers put the newly created object into a state that is completely consistent for use.
In contrast to constructors, for example, static initializers aren't inherited and are only executed once when the class is loaded and initialized by the JRE. In the example above, the class variable foo will have the value 998877 once initialization is complete.
Note also that static initializers are executed in the order in which they appear textually in the source file. Also, there are a number of restrictions on what you can't do inside one of these blocks such as no use of checked exceptions, no use of the return statement or the this and super keywords.
I want to add that static variables and static initializers are executed in order of appearance at the time of class loading. So, if your static initializer relies on some static variable, it must be initialized before the particular static block, e.g.
final static String JDBC_DRIVER = getJdbcDriver( );
static
{
try
{
Class.forName(JDBC_DRIVER);
}
catch ( ClassNotFoundException exception )
{
log.error( "ClassNotFoundException " + exception.getMessage( ) );
}
}
In this example getJdbcDriver will get executed before static initializer. Also, there may be more than 1 static initializer in the class. Once again they are executed in order of appearance.
I also want to mention the existence of instance initializers here, as they do come as surprise when seen for the first time. They look like a code block inside the class body, like this.
class MyClass
{
final int intVar;
{
intVar = 1;
}
}
In general case their use is somewhat unnecessary, because of the constructor, but they are useful in implementing Java's version of closures.
The static initializer block get executed whenever the class is to be loaded for the first time. That can happen if something at higher level is doing a Class#forName("yourpackage.YourClass") or a new YourClass() on the class in question for the first time.
By a coincidence, the decent JDBC drivers also have something similar inside. They namely registers themselves in the DriverManager using a static initializer block:
static {
DriverManager.registerDriver(new ThisDriver());
}
so that whenever you do a Class.forName("somepackage.ThisDriver"), you will effectively register the driver in the DriverManager so that you can get a connection from it afterwards.
In addition to all above , there is a minute difference in using class constructor and class initializer. Constructor as we know that will be usually used to initialized the objects and if we have static variables then static block is usually used in order to initialize them when the class will be loaded.
When we have static variables and static block then static variables initialized first and then the block.
When class is first loaded, static block initializes before the class constructor.
static initialization block
is a normal block of code
it is enclosed in braces { }
it is preceded by the static keyword
class Foo {
static {
// initialization code goes here:
doSomething();
}
}
class can have any number of static initialization blocks
they can appear anywhere in the class body
they are called in the order of apperence in the code
There is an alternative to static initialization blocks:
write a private static method
and assign it to the static class variable
The advantage of this approach is that the static method can be invoked later to reinitialize the class variable.
class Foo {
public static int myVar = initializeClassVariable();
private static int initializeClassVariable() {
// initialization code goes here:
int v = 255;
return v;
}
}
Related
I'm studying for Oracle's OCA 8 certification. In my studies, I came across an issue that left me with some doubts about the order of initialization of a Java object (static blocks, constructors, initialization of variables, ...). The question is as follows:
public class InitTest{
static String s1 = sM1("a");{
s1 = sM1("b");
}
static{
s1 = sM1("c");
}
public static void main(String args[]){
InitTest it = new InitTest();
}
private static String sM1(String s){
System.out.println(s); return s;
}
}
My question is the order in which each part of the object is started:
1) {...}
2) static {...}
3) InitTest {...}
4) static String s1 = sM1("a");
Can you explain me, please?
Order of initalization is always as follows:
initialize superclasses recursively (not relevant for the example in question since it doesn't have a superclass)
static fields and static initializers
instance fields and instance initializers
constructors
Hence, the order of initialization in your example will be:
1) static String s1 = sM1("a"); - static initialization blocks and static field members are the first to be processed, this happens just after the classloader loads the class (before you start using the class or create an object). If there are more initializers or static member declarations, they are executed in the order in which they are written. That's why this static field will get initialized before the static initializer block.
2) static {...} - explained in point 1. The static initializater comes before the declaration of static variable s1 so that's why it it is processed in this order (both have the same priority but here the order inside of the class wins if both have the same prio).
3) {...} - after the static initializers and static fields, the instance initializers and instance fields are initialized, so the instance initializer is next after the static initializer and static field s1. They are the first to be processed when creating a new object using a constructor and this happens before the constructor actually gets executed.
4.) InitTest {...} - The constructor gets called after everything else is initalized (all initialization blocks and field initializations).
More details about the class and object initialization order you can find in the Java Language Specification: https://docs.oracle.com/javase/specs/jls/se11/html/jls-12.html#jls-12.4.1, https://docs.oracle.com/javase/specs/jls/se11/html/jls-12.html#jls-12.4.2,
https://docs.oracle.com/javase/specs/jls/se11/html/jls-12.html#jls-12.5
First: The part of s1 = sM1("b") is formatted like it is part of s1 definition, but it's completely separate.
static { ... } and static String s1 =sM1("a") are both static, which means they run when the JVM loads the class, before any of the code in your Main. they are executed in the order they are written.
{...} and InitTest{...} aren't static and they run only when you create the instance of InitTest.
{...} is initialization block and run before the constructors.
Anything that's static is first taken care of as there is no reason for an object availability, The possible static contents in a class are,
a) static instance variable
b) static code block
c) static methods
and are evaluated in the same order (although order for a static method doesn't matter). So in your case the s1 = SM1("a") is evaluated first which results in the call to the sM1("a") method. Next the static code block is executed which results in sM1("c") and finally the instance code block is executed with sM1("b"). If you happen to have a no arg constructor in this class, then it would have got called as the last step before the object is available.
My question is about one particular usage of static keyword. It is possible to use static keyword to cover a code block within a class which does not belong to any function. For example following code compiles:
public class Test {
private static final int a;
static {
a = 5;
doSomething(a);
}
private static int doSomething(int x) {
return (x+5);
}
}
If you remove the static keyword it complains because the variable a is final. However it is possible to remove both final and static keywords and make it compile.
It is confusing for me in both ways. How am I supposed to have a code section that does not belong to any method? How is it possible to invoke it? In general, what is the purpose of this usage? Or better, where can I find documentation about this?
The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.
Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it's resolved, but that's a technicality).
Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.
If you remove static from int a, it becomes an instance variable, which you are not able to access from the static initializer block. This will fail to compile with the error "non-static variable a cannot be referenced from a static context".
If you also remove static from the initializer block, it then becomes an instance initializer and so int a is initialized at construction.
Uff! what is static initializer?
The static initializer is a static {} block of code inside java class, and run only one time before the constructor or main method is called.
OK! Tell me more...
is a block of code static { ... } inside any java class. and executed by virtual machine when class is called.
No return statements are supported.
No arguments are supported.
No this or super are supported.
Hmm where can I use it?
Can be used anywhere you feel ok :) that simple. But I see most of the time it is used when doing database connection, API init, Logging and etc.
Don't just bark! where is example?
package com.example.learnjava;
import java.util.ArrayList;
public class Fruit {
static {
System.out.println("Inside Static Initializer.");
// fruits array
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Pear");
// print fruits
for (String fruit : fruits) {
System.out.println(fruit);
}
System.out.println("End Static Initializer.\n");
}
public static void main(String[] args) {
System.out.println("Inside Main Method.");
}
}
Output???
Inside Static Initializer.
Apple
Orange
Pear
End Static Initializer.
Inside Main Method.
The static block is a "static initializer".
It's automatically invoked when the class is loaded, and there's no other way to invoke it (not even via Reflection).
I've personally only ever used it when writing JNI code:
class JNIGlue {
static {
System.loadLibrary("foo");
}
}
This is directly from http://www.programcreek.com/2011/10/java-class-instance-initializers/
1. Execution Order
Look at the following class, do you know which one gets executed first?
public class Foo {
//instance variable initializer
String s = "abc";
//constructor
public Foo() {
System.out.println("constructor called");
}
//static initializer
static {
System.out.println("static initializer called");
}
//instance initializer
{
System.out.println("instance initializer called");
}
public static void main(String[] args) {
new Foo();
new Foo();
}
}
Output:
static initializer called
instance initializer called
constructor called
instance initializer called
constructor called
2. How do Java instance initializer work?
The instance initializer above contains a println statement. To understand how it works, we can treat it as a variable assignment statement, e.g., b = 0. This can make it more obvious to understand.
Instead of
int b = 0, you could write
int b;
b = 0;
Therefore, instance initializers and instance variable initializers are pretty much the same.
3. When are instance initializers useful?
The use of instance initializers are rare, but still it can be a useful alternative to instance variable initializers if:
Initializer code must handle exceptions
Perform calculations that can’t be expressed with an instance variable initializer.
Of course, such code could be written in constructors. But if a class had multiple constructors, you would have to repeat the code in each constructor.
With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. (I guess this is just a concept, and it is not used often.)
Another case in which instance initializers are useful is anonymous inner classes, which can’t declare any constructors at all. (Will this be a good place to place a logging function?)
Thanks to Derhein.
Also note that Anonymous classes that implement interfaces [1] have no constructors. Therefore instance initializers are needed to execute any kinds of expressions at construction time.
"final" guarantees that a variable must be initialized before end of object initializer code. Likewise "static final" guarantees that a variable will be initialized by the end of class initialization code. Omitting the "static" from your initialization code turns it into object initialization code; thus your variable no longer satisfies its guarantees.
You will not write code into a static block that needs to be invoked anywhere in your program. If the purpose of the code is to be invoked then you must place it in a method.
You can write static initializer blocks to initialize static variables when the class is loaded but this code can be more complex..
A static initializer block looks like a method with no name, no arguments, and no return type. Since you never call it it doesn't need a name. The only time its called is when the virtual machine loads the class.
when a developer use an initializer block, the Java Compiler copies the initializer into each constructor of the current class.
Example:
the following code:
class MyClass {
private int myField = 3;
{
myField = myField + 2;
//myField is worth 5 for all instance
}
public MyClass() {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
}
public MyClass(int _myParam) {
if (_myParam > 0) {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
//if _myParam is greater than 0
} else {
myField = myField + 5;
//myField is worth 10 for all instance initialized with this construtor
//if _myParam is lower than 0 or if _myParam is worth 0
}
}
public void setMyField(int _myField) {
myField = _myField;
}
public int getMyField() {
return myField;
}
}
public class MainClass{
public static void main(String[] args) {
MyClass myFirstInstance_ = new MyClass();
System.out.println(myFirstInstance_.getMyField());//20
MyClass mySecondInstance_ = new MyClass(1);
System.out.println(mySecondInstance_.getMyField());//20
MyClass myThirdInstance_ = new MyClass(-1);
System.out.println(myThirdInstance_.getMyField());//10
}
}
is equivalent to:
class MyClass {
private int myField = 3;
public MyClass() {
myField = myField + 2;
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
}
public MyClass(int _myParam) {
myField = myField + 2;
if (_myParam > 0) {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
//if _myParam is greater than 0
} else {
myField = myField + 5;
//myField is worth 10 for all instance initialized with this construtor
//if _myParam is lower than 0 or if _myParam is worth 0
}
}
public void setMyField(int _myField) {
myField = _myField;
}
public int getMyField() {
return myField;
}
}
public class MainClass{
public static void main(String[] args) {
MyClass myFirstInstance_ = new MyClass();
System.out.println(myFirstInstance_.getMyField());//20
MyClass mySecondInstance_ = new MyClass(1);
System.out.println(mySecondInstance_.getMyField());//20
MyClass myThirdInstance_ = new MyClass(-1);
System.out.println(myThirdInstance_.getMyField());//10
}
}
I hope my example is understood by developers.
The static code block can be used to instantiate or initialize class variables (as opposed to object variables). So declaring "a" static means that is only one shared by all Test objects, and the static code block initializes "a" only once, when the Test class is first loaded, no matter how many Test objects are created.
The static initializer blocks are invoked (in the order they were defined in) when the JVM loads the class into memory, and before the main method. It's used to conditionally initialize static variables.
Similarly we have the instance initializer blocks (aka IIBs) which are invoked upon object instantiation, and they're generally used to de-duplicate constructor logic.
The order in which initializers and constructors are executed is:
Static initializer blocks;
Object initializer blocks;
Constructors;
i am trying to follow the JVM specs http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4.2.
Is frustrating for me to read the unclear specs. So:
What are the differences between:
class variable initializers
static initializers of the class
field initializers
/*
Initalizers
*/
class A {
private static String x = "sfi"; //static field initializer
private String ifi = "ifi"; //instance field initializer
static { //static (block) initalizer ?!
String y = "sbi";
}
{ //instance (block) initalizer ?!
String z = "ibi";
}
}
Static members
First you need to understand the difference between static and non-static fields of a class. A static field is not bound to any instance of the class, it is a property of the class (that is the reason why we access them through the class) so in your example you can access x from whithin A like this: A.x. A common example for this is counting the number of objects a class has:
private static int counter = 0;
public A()
{
counter++;
}
// get the instance count
public static int getCounter()
{
return counter;
}
This method we would call from somewhere else like this: A.getCounter() and we will retrieve the number of objects that have the type A.
Non-static members
These are variables that are specific to each object (instance) of the class. In your example this is sfi. The runtime system guarantees that sfi will be available whenever an object of type A is created and that it will have a default value of ifi, but the difference here is that each object you create will have a member called sfi with a default value of ifi so each object can later modify it of course.
Initializing blocks
They are a feature designed to be used when initialization cannot be done inline (initialization requires more complex logic like a for loop or error-checking). Here again we have:
static { /* init code ... /* }
which is a static initialization block that "can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code" - from here
If, on the other hand, we want to initialize instance members but we cannot do it in one line then we can use a block but without the static keyword:
{
// init code for instance members
}
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
I am getting confused with below code I expected that it will give an error or answer will be 10 but it is giving 20 how?
public class test {
public static void main(String[] args) {
System.out.println(x);
}
static{
x=10;
}
static int x=20;
}
It's specified in section 12.4.2 of the JLS, which gives details of class initialization:
Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
The variable initializer (x = 20) occurs after the static initializer (the block containing x = 10) in the program text. The value at the end of initialization is therefore 20.
If you swap the order round so that the variable initializer comes first, you'll see 10 instead.
I'd strongly advise you to avoid writing code which relies on textual ordering if possible though.
EDIT: The variable can still be used in the static initializer because it's in scope - just like you can use an instance variable in a method declared earlier than the variable. However, section 8.3.2.3 gives some restrictions on this:
The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:
The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
The usage is not on the left hand side of an assignment.
The usage is via a simple name.
C is the innermost class or interface enclosing the usage.
It is a compile-time error if any of the four requirements above are not met.
So if you change your static initializer to:
static {
System.out.println(x);
}
then you'll get an error.
Your existing static initializer uses x in a way which does comply with all of the restrictions, however.
in static if a value is changed once then it will be effected through out.
So you are getting 20.
if you write this way
public class test {
static int x=20;
public static void main(String[] args) {
System.out.println(x);
}
static{
x=10;
}
}
then it will print 10.
So I've been brushing up on my Java skills as of late and have found a few bits of functionality that I didn't know about previously. Static and Instance Initializers are two such techniques.
My question is when would one use an initializer instead of including the code in a constructor? I've thought of a couple obvious possibilities:
static/instance initializers can be used to set the value of "final" static/instance variables whereas a constructor cannot
static initializers can be used to set the value of any static variables in a class, which should be more efficient than having an "if (someStaticVar == null) // do stuff" block of code at the start of each constructor
Both of these cases assume that the code required to set these variables is more complex than simply "var = value", as otherwise there wouldn't seem to be any reason to use an initializer instead of simply setting the value when declaring the variable.
However, while these aren't trivial gains (especially the ability to set a final variable), it does seem that there are a rather limited number of situations in which an initializer should be used.
One can certainly use an initializer for a lot of what is done in a constructor, but I don't really see the reason to do so. Even if all constructors for a class share a large amount of code, the use of a private initialize() function seems to make more sense to me than using an initializer because it doesn't lock you into having that code run when writing a new constructor.
Am I missing something? Are there a number of other situations in which an initializer should be used? Or is it really just a rather limited tool to be used in very specific situations?
Static initializers are useful as cletus mentioned and I use them in the same manner. If you have a static variable that is to be initialized when the class is loaded, then a static initializer is the way to go, especially as it allows you to do a complex initialization and still have the static variable be final. This is a big win.
I find "if (someStaticVar == null) // do stuff" to be messy and error prone. If it is initialized statically and declared final, then you avoid the possibility of it being null.
However, I'm confused when you say:
static/instance initializers can be used to set the value of "final"
static/instance variables whereas a constructor cannot
I assume you are saying both:
static initializers can be used to set the value of "final" static variables whereas a constructor cannot
instance initializers can be used to set the value of "final" instance variables whereas a constructor cannot
and you are correct on the first point, wrong on the second. You can, for example, do this:
class MyClass {
private final int counter;
public MyClass(final int counter) {
this.counter = counter;
}
}
Also, when a lot of code is shared between constructors, one of the best ways to handle this is to chain constructors, providing the default values. This makes is pretty clear what is being done:
class MyClass {
private final int counter;
public MyClass() {
this(0);
}
public MyClass(final int counter) {
this.counter = counter;
}
}
Anonymous inner classes can't have a constructor (as they're anonymous), so they're a pretty natural fit for instance initializers.
I most often use static initializer blocks for setting up final static data, especially collections. For example:
public class Deck {
private final static List<String> SUITS;
static {
List<String> list = new ArrayList<String>();
list.add("Clubs");
list.add("Spades");
list.add("Hearts");
list.add("Diamonds");
SUITS = Collections.unmodifiableList(list);
}
...
}
Now this example can be done with a single line of code:
private final static List<String> SUITS =
Collections.unmodifiableList(
Arrays.asList("Clubs", "Spades", "Hearts", "Diamonds")
);
but the static version can be far neater, particularly when the items are non-trivial to initialize.
A naive implementation may also not create an unmodifiable list, which is a potential mistake. The above creates an immutable data structure that you can happily return from public methods and so on.
Just to add to some already excellent points here. The static initializer is thread safe. It is executed when the class is loaded, and thus makes for simpler static data initialization than using a constructor, in which you would need a synchronized block to check if the static data is initialized and then actually initialize it.
public class MyClass {
static private Properties propTable;
static
{
try
{
propTable.load(new FileInputStream("/data/user.prop"));
}
catch (Exception e)
{
propTable.put("user", System.getProperty("user"));
propTable.put("password", System.getProperty("password"));
}
}
versus
public class MyClass
{
public MyClass()
{
synchronized (MyClass.class)
{
if (propTable == null)
{
try
{
propTable.load(new FileInputStream("/data/user.prop"));
}
catch (Exception e)
{
propTable.put("user", System.getProperty("user"));
propTable.put("password", System.getProperty("password"));
}
}
}
}
Don't forget, you now have to synchronize at the class, not instance level. This incurs a cost for every instance constructed instead of a one time cost when the class is loaded. Plus, it's ugly ;-)
I read a whole article looking for an answer to the init order of initializers vs. their constructors. I didn't find it, so I wrote some code to check my understanding. I thought I would add this little demonstration as a comment. To test your understanding, see if you can predict the answer before reading it at the bottom.
/**
* Demonstrate order of initialization in Java.
* #author Daniel S. Wilkerson
*/
public class CtorOrder {
public static void main(String[] args) {
B a = new B();
}
}
class A {
A() {
System.out.println("A ctor");
}
}
class B extends A {
int x = initX();
int initX() {
System.out.println("B initX");
return 1;
}
B() {
super();
System.out.println("B ctor");
}
}
Output:
java CtorOrder
A ctor
B initX
B ctor
A static initializer is the equivalent of a constructor in the static context. You will certainly see that more often than an instance initializer. Sometimes you need to run code to set up the static environment.
In general, an instance initalizer is best for anonymous inner classes. Take a look at JMock's cookbook to see an innovative way to use it to make code more readable.
Sometimes, if you have some logic which is complicated to chain across constructors (say you are subclassing and you can't call this() because you need to call super()), you could avoid duplication by doing the common stuff in the instance initalizer. Instance initalizers are so rare, though, that they are a surprising syntax to many, so I avoid them and would rather make my class concrete and not anonymous if I need the constructor behavior.
JMock is an exception, because that is how the framework is intended to be used.
There is one important aspect that you have to consider in your choice:
Initializer blocks are members of the class/object, while constructors are not.
This is important when considering extension/subclassing:
Initializers are inherited by subclasses. (Though, can be shadowed)
This means it is basically guaranteed that subclasses are initialized as intended by the parent class.
Constructors are not inherited, though. (They only call super() [i.e. no parameters] implicitly or you have to make a specific super(...) call manually.)
This means it is possible that a implicit or exclicit super(...) call might not initialize the subclass as intended by the parent class.
Consider this example of an initializer block:
class ParentWithInitializer {
protected String aFieldToInitialize;
{
aFieldToInitialize = "init";
System.out.println("initializing in initializer block of: "
+ this.getClass().getSimpleName());
}
}
class ChildOfParentWithInitializer extends ParentWithInitializer{
public static void main(String... args){
System.out.println(new ChildOfParentWithInitializer().aFieldToInitialize);
}
}
output:
initializing in initializer block of: ChildOfParentWithInitializer
init
-> No matter what constructors the subclass implements, the field will be initialized.
Now consider this example with constructors:
class ParentWithConstructor {
protected String aFieldToInitialize;
// different constructors initialize the value differently:
ParentWithConstructor(){
//init a null object
aFieldToInitialize = null;
System.out.println("Constructor of "
+ this.getClass().getSimpleName() + " inits to null");
}
ParentWithConstructor(String... params) {
//init all fields to intended values
aFieldToInitialize = "intended init Value";
System.out.println("initializing in parameterized constructor of:"
+ this.getClass().getSimpleName());
}
}
class ChildOfParentWithConstructor extends ParentWithConstructor{
public static void main (String... args){
System.out.println(new ChildOfParentWithConstructor().aFieldToInitialize);
}
}
output:
Constructor of ChildOfParentWithConstructor inits to null
null
-> This will initialize the field to null by default, even though it might not be the result you wanted.
I would also like to add one point along with all the above fabulous answers . When we load a driver in JDBC using Class.forName("") the the Class loading happens and the static initializer of the Driver class gets fired and the code inside it registers Driver to Driver Manager. This is one of the significant use of static code block.
As you mentioned, it's not useful in a lot of cases and as with any less-used syntax, you probably want to avoid it just to stop the next person looking at your code from spending the 30 seconds to pull it out of the vaults.
On the other hand, it is the only way to do a few things (I think you pretty much covered those).
Static variables themselves should be somewhat avoided anyway--not always, but if you use a lot of them, or you use a lot in one class, you might find different approaches, your future self will thank you.
Note that one big issue with static initializers that perform some side effects, is that they cannot be mocked in unit tests.
I've seen libraries do that, and it's a big pain.
So it's best to keep those static initializers pure only.