Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

“Few programmers are aware of the fact that a class's constructors and methods can run prior to its initialization”

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?

like image 576
scravy Avatar asked Nov 17 '11 18:11

scravy


People also ask

What is assertion in programming?

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.

Why should you not use assertions to check parameters?

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.

What is the error thrown when assertions are enabled?

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.

Why do we use assert?

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.


1 Answers

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.

like image 88
axtavt Avatar answered Oct 15 '22 02:10

axtavt