What does the Java assert keyword do, and when should it be used?

524,370

Solution 1

Assertions (by way of the assert keyword) were added in Java 1.4. They are used to verify the correctness of an invariant in the code. They should never be triggered in production code, and are indicative of a bug or misuse of a code path. They can be activated at run-time by way of the -ea option on the java command, but are not turned on by default.

An example:

public Foo acquireFoo(int id) {
  Foo result = null;
  if (id > 50) {
    result = fooService.read(id);
  } else {
    result = new Foo(id);
  }
  assert result != null;

  return result;
}

Solution 2

Let's assume that you are supposed to write a program to control a nuclear power-plant. It is pretty obvious that even the most minor mistake could have catastrophic results, therefore your code has to be bug-free (assuming that the JVM is bug-free for the sake of the argument).

Java is not a verifiable language, which means: you cannot calculate that the result of your operation will be perfect. The main reason for this are pointers: they can point anywhere or nowhere, therefore they cannot be calculated to be of this exact value, at least not within a reasonable span of code. Given this problem, there is no way to prove that your code is correct at a whole. But what you can do is to prove that you at least find every bug when it happens.

This idea is based on the Design-by-Contract (DbC) paradigm: you first define (with mathematical precision) what your method is supposed to do, and then verify this by testing it during actual execution. Example:

// Calculates the sum of a (int) + b (int) and returns the result (int).
int sum(int a, int b) {
  return a + b;
}

While this is pretty obvious to work fine, most programmers will not see the hidden bug inside this one (hint: the Ariane V crashed because of a similar bug). Now DbC defines that you must always check the input and output of a function to verify that it worked correctly. Java can do this through assertions:

// Calculates the sum of a (int) + b (int) and returns the result (int).
int sum(int a, int b) {
    assert (Integer.MAX_VALUE - a >= b) : "Value of " + a + " + " + b + " is too large to add.";
  final int result = a + b;
    assert (result - a == b) : "Sum of " + a + " + " + b + " returned wrong sum " + result;
  return result;
}

Should this function now ever fail, you will notice it. You will know that there is a problem in your code, you know where it is and you know what caused it (similar to Exceptions). And what is even more important: you stop executing right when it happens to prevent any further code to work with wrong values and potentially cause damage to whatever it controls.

Java Exceptions are a similar concept, but they fail to verify everything. If you want even more checks (at the cost of execution speed) you need to use assertions. Doing so will bloat your code, but you can in the end deliver a product at a surprisingly short development time (the earlier you fix a bug, the lower the cost). And in addition: if there is any bug inside your code, you will detect it. There is no way of a bug slipping-through and cause issues later.

This still is not a guarantee for bug-free code, but it is much closer to that, than usual programs.

Solution 3

Assertions are a development-phase tool to catch bugs in your code. They're designed to be easily removed, so they won't exist in production code. So assertions are not part of the "solution" that you deliver to the customer. They're internal checks to make sure that the assumptions you're making are correct. The most common example is to test for null. Many methods are written like this:

void doSomething(Widget widget) {
  if (widget != null) {
    widget.someMethod(); // ...
    ... // do more stuff with this widget
  }
}

Very often in a method like this, the widget should simply never be null. So if it's null, there's a bug in your code somewhere that you need to track down. But the code above will never tell you this. So in a well-intentioned effort to write "safe" code, you're also hiding a bug. It's much better to write code like this:

/**
 * @param Widget widget Should never be null
 */
void doSomething(Widget widget) {
  assert widget != null;
  widget.someMethod(); // ...
    ... // do more stuff with this widget
}

This way, you will be sure to catch this bug early. (It's also useful to specify in the contract that this parameter should never be null.) Be sure to turn assertions on when you test your code during development. (And persuading your colleagues to do this, too is often difficult, which I find very annoying.)

Now, some of your colleagues will object to this code, arguing that you should still put in the null check to prevent an exception in production. In that case, the assertion is still useful. You can write it like this:

void doSomething(Widget widget) {
  assert widget != null;
  if (widget != null) {
    widget.someMethod(); // ...
    ... // do more stuff with this widget
  }
}

This way, your colleagues will be happy that the null check is there for production code, but during development, you're no longer hiding the bug when widget is null.

Here's a real-world example: I once wrote a method that compared two arbitrary values for equality, where either value could be null:

/**
 * Compare two values using equals(), after checking for null.
 * @param thisValue (may be null)
 * @param otherValue (may be null)
 * @return True if they are both null or if equals() returns true
 */
public static boolean compare(final Object thisValue, final Object otherValue) {
  boolean result;
  if (thisValue == null) {
    result = otherValue == null;
  } else {
    result = thisValue.equals(otherValue);
  }
  return result;
}

This code delegates the work of the equals() method in the case where thisValue is not null. But it assumes the equals() method correctly fulfills the contract of equals() by properly handling a null parameter.

A colleague objected to my code, telling me that many of our classes have buggy equals() methods that don't test for null, so I should put that check into this method. It's debatable if this is wise, or if we should force the error, so we can spot it and fix it, but I deferred to my colleague and put in a null check, which I've marked with a comment:

public static boolean compare(final Object thisValue, final Object otherValue) {
  boolean result;
  if (thisValue == null) {
    result = otherValue == null;
  } else {
    result = otherValue != null && thisValue.equals(otherValue); // questionable null check
  }
  return result;
}

The additional check here, other != null, is only necessary if the equals() method fails to check for null as required by its contract.

Rather than engage in a fruitless debate with my colleague about the wisdom of letting the buggy code stay in our code base, I simply put two assertions in the code. These assertions will let me know, during the development phase, if one of our classes fails to implement equals() properly, so I can fix it:

public static boolean compare(final Object thisValue, final Object otherValue) {
  boolean result;
  if (thisValue == null) {
    result = otherValue == null;
    assert otherValue == null || otherValue.equals(null) == false;
  } else {
    result = otherValue != null && thisValue.equals(otherValue);
    assert thisValue.equals(null) == false;
  }
  return result;
}

The important points to keep in mind are these:

  1. Assertions are development-phase tools only.

  2. The point of an assertion is to let you know if there's a bug, not just in your code, but in your code base. (The assertions here will actually flag bugs in other classes.)

  3. Even if my colleague was confident that our classes were properly written, the assertions here would still be useful. New classes will be added that might fail to test for null, and this method can flag those bugs for us.

  4. In development, you should always turn assertions on, even if the code you've written doesn't use assertions. My IDE is set to always do this by default for any new executable.

  5. The assertions don't change the behavior of the code in production, so my colleague is happy that the null check is there, and that this method will execute properly even if the equals() method is buggy. I'm happy because I will catch any buggy equals() method in development.

Also, you should test your assertion policy by putting in a temporary assertion that will fail, so you can be certain that you are notified, either through the log file or a stack trace in the output stream.

Solution 4

When should Assert be used?

A lot of good answers explaining what the assert keyword does, but few answering the real question, "when should the assert keyword be used in real life?" The answer:

Almost never

Assertions, as a concept, are wonderful. Good code has lots of if (...) throw ... statements (and their relatives like Objects.requireNonNull and Math.addExact). However, certain design decisions have greatly limited the utility of the assert keyword itself.

The driving idea behind the assert keyword is premature optimization, and the main feature is being able to easily turn off all checks. In fact, the assert checks are turned off by default.

However, it is critically important that invariant checks continue to be done in production. This is because perfect test coverage is impossible, and all production code will have bugs which assertions should help to diagnose and mitigate.

Therefore, the use of if (...) throw ... should be preferred, just as it is required for checking parameter values of public methods and for throwing IllegalArgumentException.

Occasionally, one might be tempted to write an invariant check that does take an undesirably long time to process (and is called often enough for it to matter). However, such checks will slow down testing which is also undesirable. Such time-consuming checks are usually written as unit tests. Nevertheless, it may sometimes make sense to use assert for this reason.

Do not use assert simply because it is cleaner and prettier than if (...) throw ... (and I say that with great pain, because I like clean and pretty). If you just cannot help yourself, and can control how your application is launched, then feel free to use assert but always enable assertions in production. Admittedly, this is what I tend to do. I am pushing for a lombok annotation that will cause assert to act more like if (...) throw .... Vote for it here.

(Rant: the JVM devs were a bunch of awful, prematurely optimizing coders. That is why you hear about so many security issues in the Java plugin and JVM. They refused to include basic checks and assertions in production code, and we are continuing to pay the price.)

Solution 5

Here's the most common use case. Suppose you're switching on an enum value:

switch (fruit) {
  case apple:
    // do something
    break;
  case pear:
    // do something
    break;
  case banana:
    // do something
    break;
}

As long as you handle every case, you're fine. But someday, somebody will add fig to your enum and forget to add it to your switch statement. This produces a bug that may get tricky to catch, because the effects won't be felt until after you've left the switch statement. But if you write your switch like this, you can catch it immediately:

switch (fruit) {
  case apple:
    // do something
    break;
  case pear:
    // do something
    break;
  case banana:
    // do something
    break;
  default:
    assert false : "Missing enum value: " + fruit;
}
Share:
524,370
Praveen
Author by

Praveen

Android, iOS and React Native Developer

Updated on July 21, 2021

Comments

  • Praveen
    Praveen over 2 years

    What are some real life examples to understand the key role of assertions?

  • Konerak
    Konerak almost 14 years
    This would be frowned upon in C: An assertion is something that REALLY NEVER should happen - popping an empty stack should throw a NoElementsException or something along the lines. See Donal's reply.
  • DJClayworth
    DJClayworth almost 14 years
    I agree. Even though this is taken from an official tutorial, it's a bad example.
  • DJClayworth
    DJClayworth almost 14 years
    You don't have to call hasNext() before next().
  • Donal Fellows
    Donal Fellows almost 14 years
    @DJClayworth: You don't need to avoid triggering assertions either. :-)
  • Aram Kocharyan
    Aram Kocharyan about 11 years
  • SJuan76
    SJuan76 over 10 years
    In fact, Oracle tells you not to use assert to check public method parameters (docs.oracle.com/javase/1.4.2/docs/guide/lang/assert.html). That should throw an Exception instead of killing the program.
  • TwoThe
    TwoThe over 10 years
    I chose this example because it presents hidden bugs in seemingly bug-free code very well . If this is similar to what someone else presented, then they maybe had the same idea in mind. ;)
  • Tony Chan
    Tony Chan over 10 years
    I still don't understand why choose to use assert instead of just some if conditions? And to trigger these asserts you have to hit those edge cases while testing, which doesn't always happen. So what happens in production environments where assert is ignored?
  • Eric Tobias
    Eric Tobias over 10 years
    You choose assert because it fails when the assertion is false. An if can have any behaviour. Hitting fringe cases is the job of Unit Testing. Using Design by Contract specified the contract rather well but as with real life contracts, you need a control to be sure they are respected. With assertions a watchdog is inserted that will then you when the contract is disrespected. Think of it as a nagging lawyer screaming "WRONG" every time you do something that is outside or against a contract you signed and then send you home so you can't continue to work and breach the contract further!
  • TwoThe
    TwoThe over 10 years
    The benefit of assert vs if is that you can specify a condition at runtime, that causes the JVM to completely ignore all assert statements as if they didn't exist, for an obvious performance gain. This is especially helpful if your asserts do some heavy calculation to determine their true/false state. You should however not disable asserts because they fail. In this case you should fix the code!
  • jantristanmilan
    jantristanmilan over 10 years
    @TwoThe outside the topic of assertion, is the second assert really necessary? Haha I cant think of a scenario where it would return the wrong result.
  • TwoThe
    TwoThe over 10 years
    Necessary in this simple case: no, but the DbC defines that every result must be checked. Imagine someone now modifies that function to something much more complex, then he has to adapt the post-check as well, and then it suddenly becomes useful.
  • H.Rabiee
    H.Rabiee about 10 years
    There's probably a memory leak there. You should set stack[num] = null; in order for the GC to do its job properly.
  • Blueriver
    Blueriver about 10 years
    Sorry to resurrect this, but I have a specific question. What is the difference between what @TwoThe did and instead of using assert just throwing a new IllegalArgumentException with the message? I mean, aside from having o add throws to the method declaration and the code to manage that exception somewhere else. Why assert insetad of throwing new Exception? Or why not an if instead of assert? Can't really get this :(
  • TwoThe
    TwoThe about 10 years
    There could be a try {} catch (Throwable t) somewhere in the code that would hide such exceptions. And you could do if (...) (in some languages assertions are even coded like that), but what do you do in the error case? Either your if would just duplicate what assertions are doing, or you would lower the effect of them. One purpose of assertions is that they poke you in the eye and scream "FIX ME!!" until you do it. Assert vs laziness so to say.
  • kevin cline
    kevin cline over 9 years
    -1: The assertion to check for overflow is wrong if a can be negative. The second assertion is useless; for int values, it is always the case that a + b - b == a. That test can only fail if the computer is fundamentally broken. To defend against that contingency, you need to check for consistency across multiple CPUs.
  • Vlasec
    Vlasec over 9 years
    I think in a private method, it would be correct to use an assertion, as it would be weird to have exceptions for a malfunction of a class or method. In a public method, calling it from somewhere outside, you can't really tell how the other code uses it. Does it really check isEmpty() or not? You don't know.
  • AMDG
    AMDG over 9 years
    an if-statement can emulate an assert as well, but what about vice-versa? If you used assert as an if-statement could you use it instead of if?
  • Mike Nakis
    Mike Nakis over 9 years
    That's why you should have warnings enabled and warnings treated as errors. Any halfway decent compiler is capable of telling you, if only you allow it to tell you, that you are missing an enum check, and it will do so at compile time, which is unspeakably better than (perhaps, one day) finding out at run time.
  • Opher
    Opher about 9 years
    Hey, your example proper makes an unobvious assumption. It assumes the contract of 'fooService.read(int)' is to never return null.
  • liltitus27
    liltitus27 almost 9 years
    why use an assertion here rather than an exception of some sort, e.g., an illegalargumentexception?
  • Evgeni Sergeev
    Evgeni Sergeev over 8 years
    So the catch (Throwable t) clause is able to catch assertion violations too? For me that limits their utility just to the case where the body of the assertion is time-consuming, which is rare.
  • El Mac
    El Mac about 8 years
    But you still don't explain why they exist. Why can't you do an if() check and throw an exception?
  • aioobe
    aioobe about 8 years
    This will throw an AssertionError if assertions are enabled (-ea). What is the desired behavior in production? A silent no-op and potential disaster later in the execution? Probably not. I would suggest an explicit throw new AssertionError("Missing enum value: " + fruit);.
  • hoodaticus
    hoodaticus about 8 years
    @ElMac - assertions are for the dev/debug/test parts of the cycle - they are not for production. An if block runs in prod. Simple assertions won't break the bank, but expensive assertions that do complex data validation might bring down your production environment, which is why they are turned off there.
  • El Mac
    El Mac about 8 years
    @hoodaticus you mean solely the fact that I can turn on/off all assertions for prod code is the reason? Because I can do complex data validation anyways and then handle it with exceptions. If I have production code, I could turn off the complex (and maybe expensive) assertions, because it should work and was tested already? In theory they shouldnt bring down the program because then you would have a problem anyways.
  • MiguelMunoz
    MiguelMunoz almost 8 years
    There's a good argument to be made for just throwing an AssertionError. As for the proper behavior in production, the whole point of assertions is to keep this from happening in production. Assertions are a development phase tool to catch bugs, which can easily be removed from production code. In this case, there's no reason to remove it from production code. But in many cases, integrity tests may slow things down. By putting these test inside assertions, which aren't used in production code, you are free to write thorough tests, without worrying that they will slow down your production code.
  • XaolingBao
    XaolingBao almost 8 years
    Interesting comments, but I'm curious where this comment that "Java isn't verifiable" comes from, or why you think so? You speak about pointers, and where they are pointing, but if there's a problem, then wouldn't code break all of the time?
  • TwoThe
    TwoThe almost 8 years
    Verifiable with mathematic precision would be more accurate. There is a whole area in computer science that tries to figure out how you can not only assume but (at compile-time) proof that you program is doing what it should be doing (see Ada Spark for example). This is easy to do for small pieces of code with limited reach, but as soon as you introduce global variables, or worse: global variables that not only hold one value but point to an object with many values, or even worse several other pointers as well, the whole construct gets so complicated, that the task becomes unmanageable.
  • Aleksandr Dubinsky
    Aleksandr Dubinsky almost 8 years
    "And what is even more important: you stop executing right when it happens to prevent any further code to work with wrong values" -- except that assertions are disabled by default. I really wish they'd made a different decision there.
  • Tuntable
    Tuntable almost 8 years
    Spot on. But it is actually worse than that because it throws an AssertionError instead of an Exception that might be trapped, logged, recovered etc. by higher level code. (Think of a web app that has a bug.)
  • Aleksandr Dubinsky
    Aleksandr Dubinsky almost 8 years
    @aberglas A catch-all clause is catch (Throwable t). There is no reason to not try to trap, log, or retry/recover from OutOfMemoryError, AssertionError, etc.
  • raspacorp
    raspacorp almost 8 years
    @AleksandrDubinsky The reality is that the common practice (I am not saying it is the right one) is to use catch (Exception e) as a catch-all statement, that is what is commonly found. Assertions wouldn't get caught by that, I think that is what aberglas is talking about
  • MiguelMunoz
    MiguelMunoz over 7 years
    I'm not sure why it limits the assertion's usefulness. You shouldn't ever catch a Throwable except in very rare cases. If you do need to catch Throwable but want it to not catch assertions, you can just catch the AssertionError first and rethrow it.
  • MiguelMunoz
    MiguelMunoz over 7 years
    I have caught and recovered from OutOfMemoryError.
  • MiguelMunoz
    MiguelMunoz over 7 years
    I agree. The article has many excellent examples. I especially liked the one to make sure a method is only called when the object holds a lock.
  • MiguelMunoz
    MiguelMunoz over 7 years
    I don't agree. Many of my assertions are used to make sure my API is getting called correctly. For example, I might write a private method that should only be called when an object holds a lock. If another developer calls that method from part of the code that doesn't lock the object, the assertion will tell them right away that they made a mistake. There are a lot of mistakes like this that can, with certainty, get caught in the development phase, and assertions are very useful in these cases.
  • Aleksandr Dubinsky
    Aleksandr Dubinsky over 7 years
    @MiguelMunoz In my answer I said that the idea of assertions is very good. It is the implementation of the assert keyword is bad. I will edit my answer to make it more clear that I am referring to the keyword, not the concept.
  • rubenafo
    rubenafo about 7 years
    It doesn't provide any real life example, which is the aim of the question
  • MiguelMunoz
    MiguelMunoz almost 7 years
    I like the fact that it throws an AssertionError instead of an Exception. Too many developers still haven't learned that they shouldn't catch Exception if the code can only throw something like IOException. I've had bugs in my code get completely swallowed because somebody caught Exception. Assertions don't get caught in this trap. Exceptions are for situations that you expect to see in production code. As for logging, you should be logging all your errors too, even though errors are rare. For example, do you really want to let an OutOfMemoryError pass without logging it?
  • Koray Tugay
    Koray Tugay almost 7 years
    The code you have written would not help crashing of Ariane V.
  • Koray Tugay
    Koray Tugay almost 7 years
  • Bakhshi
    Bakhshi over 6 years
    This convention is unaffected by the addition of the assert construct. Do not use assertions to check the parameters of a public method. An assert is inappropriate because the method guarantees that it will always enforce the argument checks. It must check its arguments whether or not assertions are enabled. Further, the assert construct does not throw an exception of the specified type. It can throw only an AssertionError. docs.oracle.com/javase/8/docs/technotes/guides/language/…
  • Aleksandr Dubinsky
    Aleksandr Dubinsky about 6 years
    @Konerak Popping this stack should also "really never" happen if its contract forbids it. Exceptions need to have distinct names if you expect to catch and handle them. If an error such as popping this stack should be fixed in code instead of handled at runtime, then it's fine to make it raise an assertion.
  • Josef.B
    Josef.B almost 6 years
    Great answer, but not relevant to the 'assert' keyword? Asserts can be turned off, so any DbC code using it is fruitless. DbC requires actual run-time code.
  • TwoThe
    TwoThe almost 6 years
    Can be turned off doesn't mean they are by default. Turning them off is a performance feature you can use if you are certain that your code runs fine, otherwise they will be checked.
  • Brent Bradburn
    Brent Bradburn over 5 years
    Good points about "hiding a bug" and how asserts expose bugs during development!
  • maaartinus
    maaartinus over 5 years
    I strongly doubt that using such a tiny a HashSet brings any speed advantage over an ArrayList. Moreover, the set and list creations dominate the lookup time. They'd fine when using a constant. That all said, +1.
  • Ayaz Pasha
    Ayaz Pasha over 5 years
    To enable assertion in eclipse IDE, please follow tutoringcenter.cs.usfca.edu/resources/…
  • MiguelMunoz
    MiguelMunoz over 4 years
    I don't think there's a way to turn on asserts in Android. This is very disappointing.
  • MiguelMunoz
    MiguelMunoz over 4 years
    All true. I did it this inefficient way to illustrate my point that assertions are free to be slow. This one could be made more efficient, but there are others that can't. In an excellent book called "Writing Solid Code," Steve Maguire tells of an assertion in Microsoft Excel to test the new incremental-update code that skipped cells that shouldn't change. Every time the user made a change, the assertion would recalculate the entire spreadsheet to make sure the results matched those by the incremental-update feature. It really slowed the debug version, but they caught all their bugs early.
  • MiguelMunoz
    MiguelMunoz over 4 years
    @Blueriver @Tony Chan The difference between using an assert and throwing an IllegalArgumentException is that the assertion will most likely be off in production. The whole point of assertions is that you can leave them off once you're confident in your code. Assertions are strictly a development-phase tool. They help you catch bugs earlier in the development cycle.
  • maaartinus
    maaartinus over 4 years
    Fully agreed. Assertions are sort of tests - they're less versatile than ordinary tests, but they can cover private methods and they're much cheaper to write. I'll try to use them even more.
  • maaartinus
    maaartinus over 4 years
    I strongly disagree. You want assertions to be something else, but there are already Preconditions and Verify in Guava and whatever. Assertions (as designed in Java) are sort of tests - not to be run in production. They're much cheaper to write than tests; they can't replace tests but they complement them nicely. They can check conditions which are too expensive to be checked in production. They must not be misused for preconditions.
  • maaartinus
    maaartinus over 4 years
    This seems to be wrong. IMHO you should not use default so that the compiler can warn you on missing cases. You can return instead of break (this may need extracting the method) and then handle the missing case after the switch. This way you get both the warning and an opportunity to assert.
  • Aleksandr Dubinsky
    Aleksandr Dubinsky over 4 years
    @maaartinus What conditions are too expensive to check in production? Can you give examples what you use assertions for?
  • maaartinus
    maaartinus over 4 years
    @AleksandrDubinsky See this comment and my answer for real world usage (not mine). In my code, there are things like assert Sets.newHashSet(userIds).size() == userIds.size() where I'm pretty sure that the list I just created has unique elements, but I wanted to document and double check it (I really need a list here, no set; the check here is rather cheap, but also rather superfluous).
  • Aleksandr Dubinsky
    Aleksandr Dubinsky over 4 years
    @maaartinus The example of Excel does give food for thought. However, your check for user id uniqueness should probably be enabled in production code.
  • Aleksandr Dubinsky
    Aleksandr Dubinsky over 4 years
    None of these checks are slow, so there is no reason to turn them off in production. They should be converted into logging statements, so that you could detect problems that don't show up in your "development phase." (Really, there is no such thing as a development phase, anyway. Development ends when you decide to stop maintaining your code at all.)
  • Ashutosh
    Ashutosh about 3 years
    So does this mean assert can be used in production ready code?
  • TwoThe
    TwoThe about 3 years
    @Ashutosh Against all odds: yes, and you should do that. Many people disable those in production and with that their best chance to find bugs. Now of course your program should be hardened enough so that a single AssertionException does not lead to a total crash of the system, but to a way of informing the devs about the error followed by a proper recovery.
  • Ilya Serbis
    Ilya Serbis over 2 years
    Oracle guide states that assertions should not be used for checking contracts! "Argument checking is typically part of the published specifications (or contract) of a method, and these specifications must be obeyed whether assertions are enabled or disabled" (and, as @AleksandrDubinsky noted, assertions are disabled by default!)