Is Java assert broken?

2019-02-04 07:25发布

While poking around the questions, I recently discovered the assert keyword in Java. At first, I was excited. Something useful I didn't already know! A more efficient way for me to check the validity of input parameters! Yay learning!

But then I took a closer look, and my enthusiasm was not so much "tempered" as "snuffed-out completely" by one simple fact: you can turn assertions off.*

This sounds like a nightmare. If I'm asserting that I don't want the code to keep going if the input listOfStuff is null, why on earth would I want that assertion ignored? It sounds like if I'm debugging a piece of production code and suspect that listOfStuff may have been erroneously passed a null but don't see any logfile evidence of that assertion being triggered, I can't trust that listOfStuff actually got sent a valid value; I also have to account for the possibility that assertions may have been turned off entirely.

And this assumes that I'm the one debugging the code. Somebody unfamiliar with assertions might see that and assume (quite reasonably) that if the assertion message doesn't appear in the log, listOfStuff couldn't be the problem. If your first encounter with assert was in the wild, would it even occur to you that it could be turned-off entirely? It's not like there's a command-line option that lets you disable try/catch blocks, after all.

All of which brings me to my question (and this is a question, not an excuse for a rant! I promise!):

What am I missing?

Is there some nuance that renders Java's implementation of assert far more useful than I'm giving it credit for? Is the ability to enable/disable it from the command line actually incredibly valuable in some contexts? Am I misconceptualizing it somehow when I envision using it in production code in lieu of statements like if (listOfStuff == null) barf();?

I just feel like there's something important here that I'm not getting.

*Okay, technically speaking, they're actually off by default; you have to go out of your way to turn them on. But still, you can knock them out entirely.


Edit: Enlightenment requested, enlightenment received.

The notion that assert is first and foremost a debugging tool goes a long, long way towards making it make sense to me.

I still take issue with the notion that input checks for non-trivial private methods should be disabled in a production environment because the developer thinks the bad inputs are impossible. In my experience, mature production code is a mad, sprawling thing, developed over the course of years by people with varying degrees of skill targeted to rapidly changing requirements of varying degrees of sanity. And even if the bad input really is impossible, a piece of sloppy maintenance coding six months from now can change that. The link gustafc provided (thanks!) includes this as an example:

assert interval > 0 && interval <= 1000/MAX_REFRESH_RATE : interval;

Disabling such a simple check in production strikes me as foolishly optimistic. However, this is a difference in coding philosophy, not a broken feature.

In addition, I can definitely see the value of something like this:

assert reallyExpensiveSanityCheck(someObject) : someObject;

My thanks to everybody who took the time to help me understand this feature; it is very much appreciated.

12条回答
虎瘦雄心在
2楼-- · 2019-02-04 07:49

Assertions are meant to ensure things you are sure that your code fulfills really are fulfilled. It's an aid in debugging, in the development phase of the product, and is usually omitted when the code is released.

What am I missing?

You're not using assertions the way they were meant to be used. You said "check the validity of input parameters" - that's precisely the sort of things you do not want to verify with assertions.

The idea is that if an assertion fails, you 100% have a bug in your code. Assertions are often used for identifying the bug earlier than it would have surfaced otherwise.

查看更多
贪生不怕死
3楼-- · 2019-02-04 07:51

Assertions are to indicate a problem in the code that may be recoverable, or as an aid in debugging. You should use a more destructive mechanism for more serious errors, such as stopping the program.

They can also be used to catch an unrecoverable error before the application fails later in debugging and testing scenarios to help you narrow down a problem. Part of the reason for this is so that integrity checking does not reduce the performance of well-tested code in production.

Also, in certain cases, such as a resource leak, the situation may not be desirable, but the consequences of stopping the program are worse than the consequences of continuing on.

查看更多
Ridiculous、
4楼-- · 2019-02-04 07:54

I think its the way assert usage is interpreted and envisioned.

If you really want to add the check in your actual production code, why not use If directly or any other conditional statement?

Those being already present in language, the idea of assert was only to have developer's add assertions only if they don't really expect this condition to ever happen.

E.g checking an object to be null, let's say a developer wrote a private method and called it from two places (this is not ideal example but may works for private methods) in the class where he knows he passes a not null object, instead of adding unnecessary check of if since as of today you know there is no way object would be null But if someone tomorrow calls this method with null argument, in developer's unit testing this can be caught due to presence of assertion and in final code you still don't need an if check.

查看更多
一夜七次
5楼-- · 2019-02-04 07:54

Assertions are really a great and concise documentation tool for a code maintainer.

For example I can write:

foo should be non-null and greater than 0

or put this into the body of the program:

assert foo != null;
assert foo.value > 0;

They are extremely valuable for documenting private/package private methods to express original programmer invariants.

For the added bonus, when the subsystem starts to behave flaky, you can turn asserts on and add extra validation instantly.

查看更多
来,给爷笑一个
6楼-- · 2019-02-04 08:00

This doesn't directly answer your question about assert, but I'd recommend checking out the Preconditions class in guava/google-collections. It allows you to write nice stuff like this (using static imports):

// throw NPE if listOfStuff is null
this.listOfStuff = checkNotNull(listOfStuff);

// same, but the NPE will have "listOfStuff" as its message
this.listOfStuff = checkNotNull(listOfStuff, "listOfStuff"); 

It seems like something like this might be what you want (and it can't be turned off).

查看更多
ら.Afraid
7楼-- · 2019-02-04 08:01

Every language I've ever seen with assertions comes with the capability of shutting them off. When you write an assertion you should be thinking "this is silly, there's no way in the universe this could ever be false" -- if you think it could be false, it should be an error check. The assertion is just to help you during development if something goes horribly wrong; when you build the code for production you disable them to save time and avoid (hopefully) superfluous checks

查看更多
登录 后发表回答