With following codes,
public Some persist(final Some entity) {
if (flag) {
super.persist(entity);
entity.credentials();
update(entity);
return entity;
}
assert super.persist(entity).equals(entity);
assert entity.credentials().equals(entity);
assert update(entity);
return entity;
}
if the flag is false, it seems statements are ignored and not executed.
Is it normal? Or some assertion failed?
I already know how to enable assertion.
What I want to know is that the whole assert ... statement is ignored or not regardless of enabling the -ea option.
I'm trying them with my spring library and it seems that the whole statement which means the code yielding the boolean flag are ignored.
What I want to know is that
I'm sharing what I learned. It's pretty shocking to me.
public Some persist(final Some entity) {
// WORKS!
super.persist(entity);
entity.generate();
update(entity);
return entity;
// WORKS!
final Some persisted = super.persist(entity);
assert persisted.equals(entity);
final Some generated = entity.credentials();
assert generated.equals(persisted);
final boolean updated = update(generated);
assert updated;
return generated;
// DOES NOT WORK!!! SHOULDN'T DO THIS!!!
assert super.persist(entity).equals(entity);
assert entity.generate().equals(entity);
assert update(entity);
return entity;
}
What I want to know is that the whole assert ... statement is ignored or not regardless of enabling the -ea option.
Yes, it will be ignored entirely unless assertions are enabled. This is useful as a way to detect whether they're enabled at runtime:
boolean assertionsEnabled = false;
assert assertionsEnabled = true;
System.out.println("Assertions enabled: " + assertionsEnabled);
You got to enable assertions. Assertions can be enabled or disabled when the program is started, and are disabled by default.
Disabling assertions eliminates their performance penalty entirely. Once disabled, they are essentially equivalent to empty statements in semantics and performance. You may want to test your code on fly in dev but do not want to decrease your performance in prod without changing any code.
Is the only the functionality of assertion ignored
I guess that is the whole point of assertions, that it enables you to test your assumptions about your program.
The whole statement are ignored
Yes, When Java program is compiled, with assertions enabled/disabled, it is marked in the generated class file. So when class-loader loads your file and run the instruction or line is completely ignored if assertions were disabled.
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