问题
There are several questions on StackOverflow discussing the question of when one should use an assert statement versus throwing some exception. (Examples here, here, here, here, and here.
However, I have come to suspect that the conventional wisdom of assert-versus-throw is based upon the assumption that you are running within a JVM. In the GWT universe, where your Java gets transliterated to JavaScript and runs in the context of a browser, the set of tradeoffs feels different: asserts are always compiled-away when running in a browser, and anything that keeps the size of your JavaScript smaller is a win, especially if you web application must run on a mobile handset. Asserts do get run in DevMode, however, so they have utility there during development.
So my questions are: has anybody given any thought as to a set of best-practice rules that govern how to use the assert statement in GWT? I have had members of my team ask me "since the assert gets compiled out, does it make sense to have them?", and I'd like to have a good answer for them.
Also, does anybody have any insight into the philosophy that the developers of GWT at Google have on this subject? Looking at the GWT source code, they appear to use it frequently.
回答1:
Google's FAQ says
Only use assertions for debugging purposes, not production logic because assertions will only work under GWT's development mode. By default, they are compiled away by the GWT compiler so do not have any effect in production mode unless you explicitly enable them.
This isn't any different from the answers given to the questions you linked to. Whether the Java code is being compiled in the usual way by javac or being compiled to JavaScript by GWT, "assert" means "if this isn't true I have a bug." In contrast, code of the form
if (condition) throw new Exception(msg);
means "if this is true then we have an unexpected situation that the program will have to handle."
As for the members of the team that don't see the point of assert, explain that they're supposed to have a bunch of unit tests that run with assertions enabled. If the tests have good code coverage and none of them cause the assertion to fail, then the assumption indicated by the assert statement is demonstrated to hold.
回答2:
The GWT compiler removes them by default, but you can leave them in if you like. If you think assertions are useful in compiled code, add the -ea command line argument when invoking com.google.gwt.dev.Compiler. The compiler will then turn the Java asserts 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
来源:https://stackoverflow.com/questions/6023309/when-to-use-assert-in-client-common-gwt-code