In the official Java guide “Programming with assertions” it is stated that (last paragraph on the page)
Few programmers are aware of the fact that a class's constructors and methods can run prior to its initialization. When this happens, it is quite likely that the class's invariants have not yet been established, which can cause serious and subtle bugs.
What is meant by this? When does this happen? Is it something I have to care about in my daily use of Java?
An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.
Do not use assertions to check the parameters of a public method. An assert is inappropriate because the method guarantees that it will always enforce the argument checks. It must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type.
If assertions are enabled and the boolea n expression is false, an AssertionError is thrown. If assertions are disabled, no matter the outcome of the boolean expression, assertions are ignored.
Assertions are mainly used to check logically impossible situations. For example, they can be used to check the state a code expects before it starts running or the state after it finishes running. Unlike normal exception/error handling, assertions are generally disabled at run-time.
Basically, they talk about the following situation:
public class Foo {
public static Foo INSTANCE = new Foo(); // Prints null
public static String s = "bar";
public Foo() {
System.out.println(s);
}
}
As you can see, in this case constructor runs before initializer of the static field s
, i. e. prior to the full initialization of the class. It's just a simple example, but it can become more complex when multiple classes are involved.
It's not something you can often see in your everyday work, but you need to be aware of this possibility and avoid it when writing code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With