When to use assert in GWT client & generic code

There are several questions in StackOverflow that discuss when to use the assert statement or throw an exception. (Examples here , here , here , here and here .

However, I came to the conclusion that the generally accepted wisdom of assert-versus-throw is based on the assumption that you are working in the JVM. In the GWT universe, where your Java is transliterated into JavaScript and works in a browser context, the set of compromises is different from the others: statements are always compiled when launched in the browser and everything that reduces the size of your JavaScript less is a victory, especially if the web application should run on a mobile the phone. However, make sure they run in DevMode, so they have a utility during development.

So my questions are: did anyone think of a set of best practice rules that determine how to use the assert statement in GWT? I had members of my team who ask me: β€œSince the statement is compiled, does it make sense to have them?”, And I would like to get a good answer for them.

Also, does anyone have an idea of ​​the philosophy that GWT developers at Google have on this subject? Looking at the source code for GWT, they often use it.

+8
java assert gwt design-by-contract
source share
2 answers

Google FAQ says

Use only statements for debugging purposes, not for production logic, since statements will only work in GWT design mode. By default, they are compiled by the GWT compiler, so they have no effect in run mode unless you explicitly enable them.

This is no different than answering the questions you are associated with. Regardless of whether Java code compiles in the usual way using javac or compiles in JavaScript GWT, "assert" means "if it is not, I have an error." In contrast, the form code

if (condition) throw new Exception(msg); 

means "if this is true, then we have an unforeseen situation with which the program will work."

For team members who do not see the approval point, explain that they must have a bunch of unit tests that run with the statements included. If the tests have good code coverage, and none of them lead to a failure of the statement, then the assumption indicated by the statement is demonstrated.

+14
source share

The GWT compiler removes them by default, but you can leave them if you want. If you think the statements are useful in the compiled code, add the -ea command line argument when calling com.google.gwt.dev.Compiler. Then the compiler will turn Java into JavaScript.

 Google Web Toolkit 2.3.0 Compiler [-logLevel level] [-workDir dir] [-gen dir] [-style style] [-ea] [-XdisableClassMetadata] [-XdisableCastChecking] [-validateOnly] [-draftCompile] [-optimize level] [-compileReport] [-strict] [-localWorkers count] [-war dir] [-deploy dir] [-extra dir] module[s] ... -ea Debugging: causes the compiled output to check assert statements 
+4
source share

All Articles