Domanda

In javaFx, we see the following statement in the initialize method of each generated controller class, for each control with fxid.

assert type != null : "fx:id=\"type\" was not injected: check your FXML file 'FinancialReport.fxml'.";

I can understand that the statement is there to ensure that, at the time this fxml is loaded the control with this fx:id is present in the fxml layout file, if the control is not present it throws an exceptions and quits the fxml loading process.

But then referring to this, I learned that assertions are not recommended to be used in production code. Again studying this tutorial, it seems that assertions are useful, especially when debugging (however, not to be used to validate the arguments of public methods).

I need more knowledge of the following :

  1. Is it fine to use assertions for input validation and such purposes, in production code?
  2. Can we do something else then the usual behavior when the Boolean expression turns false, like some alternative method call or something (an example would be nice).
È stato utile?

Soluzione

Is it fine to use assertions for input validation and such purposes, in production code?

No. Refer to the first link you posted (which actually says that assertions should never be triggered in production code, not that they should never be used): assertions are not even switched on by default when running the JVM. So your validation would fail most of the time. Assertions are specifically there as a debugging tool - to check that your code is correct. The assertions that are added in the generated controller code are good examples: they check that the @FXML-annotated fields in the controller have elements in the FXML file with matching fx:id attributes. If this fails, it's a programming error, not a data validation error.

Can we do something else then the usual behavior when the Boolean expression turns false, like some alternative method call or something (an example would be nice).

Just use an if (...) { ... } else { ... } construct?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top