Search code examples
javaruntimecompile-time

What doess compile time safety and run time safety mean?



According to this post about Java Enum, runtime-safety can achieved by using ==operator to compare status and prevent NullPointerException.

if(testPz.getStatus() == Pizza.PizzaStatus.DELIVERED); 

Also for compile-time-safety although logically the comparison was proved false, this issue is avoided by using the == operator.

if(testPz.getStatus() == TestColor.GREEN);

Can you please tell me what compile-time-safety and runtime-safety are in Java?

If you can please give me a small example.


Solution

  • In general, compile-time safety means that your code follows the rules of the language, while runtime safety means that your code does the right thing. Different languages provide different sets of rules and thus different safety guarantees.

    Compile-time safety means that the compiler can analyze your code and guarantee that certain kinds of errors are not present. In Java, a common example is type safety (it is guaranteed that an object in a variable of type List is some kind of list implementation). Some languages, such as Kotlin on the JVM, can also guarantee that null-pointer exceptions can't occur because nullable and not-null variables are identified, and explicit checks are required.

    Compile-time safety has its limits, however; for example, you can use a cast in Java to specifically tell the compiler that "I know the object here is of a certain type, even though you can't prove it", and if you're wrong, you can get a ClassCastException when you run the program.

    The article you linked to is talking about my second example, null safety. In Java, a variable of a reference type can have the value null, which doesn't actually refer to a real instance, and if you try to call a method on that variable, you get a NullPointerException. In this example, if you have an enum Status, then if you call statusVariable.equals(VALUE), then you'll get an exception if statusVariable is null: The expression is compile-time safe, but not runtime-safe, because Java doesn't make guarantees about null values. In contrast, == is safe to use with null values, so even if your variable is null, you will get result of false instead of an exception.