16

I have never understood what is assert used for, even though I have read plenty examples, they don't really let me know what or why should I use it for.

So Instead of asking an example, I'm gonna provide one and let me know if this is the proper usage of assert.

// The idea is that the `mode` variable should be 0 or 1, and no other number.
switch(mode) {
     case 0: 
          // do stuff
          break;
     case 1:
          // do other stuff
          break;

     default:
          // assert code?
}

If this is correct, please let me know how to use it in this case. If this is not how it is supposed to use, please provide an example.

Makoto
  • 104,088
  • 27
  • 192
  • 230
Christopher Francisco
  • 15,672
  • 28
  • 94
  • 206
  • possible duplicate of [What does assert do?](http://stackoverflow.com/questions/3018683/what-does-assert-do) – Matt Ball Sep 20 '13 at 01:32
  • 1
    You assert boolean expressions which you assume must be true. You make assumptions when you write code and you have be aware of what they are. – Peter Lawrey Sep 20 '13 at 01:52

3 Answers3

19

Not in this case.

If you're asserting a value, you're making a statement that, before some critical evaluation is done using this value, that it is what you assert it to be. You can assert that the value isn't null, or that it's less than 2, or something before you reach your critical code block.

assert (mode >= 0 && mode < 2);  // Ensures that `mode` is between 0 and 1.
// Switch statement to follow

I would not encourage the use of that here. Your code would not read well, and unless you enable assertions with the -ea flag, your assertion would not work.

Instead, what you can do is throw an exception of some kind - if it's not 0 or 1, then the mode is an illegal value which cannot be processed, leading to exceptional/undefined behavior. Throw an exception of some kind.

switch(mode) {
    case 0: 
        // do stuff
        break;
    case 1:
        // do other stuff
        break;
    default:
      throw new IllegalArgumentException("Mode is illegal");
}
Makoto
  • 104,088
  • 27
  • 192
  • 230
  • 2
    +1 to offset; throwing an exception, IMO, would be preferable to an `assert`. What if asserts are turned off? E.g., the default? – Dave Newton Sep 20 '13 at 01:30
  • @DaveNewton While I agree with you regarding the exception, it's important to note that asserts have a self-documenting effect. There are times when it's appropriate and beneficial to have an `assert` even if you are *certain* that its condition will never be false. – arshajii Sep 20 '13 at 01:34
  • @arshajii: I do not personally feel that this is such a time. If there's ever any doubt, throwing an explicit exception and forcing the caller to deal with this issue is more preferable; if assertions are disabled, then those conditions may slip by unchecked. – Makoto Sep 20 '13 at 01:36
  • @Makoto Yes, I agree, as I stated in my comment. +1 as well. – arshajii Sep 20 '13 at 01:36
  • 2
    @arshajii If you're certain the condition will never be false then throwing an exception is just as self-documenting, and doesn't rely on assertions being explicitly enabled. Asserts are a development-time tool; something that could go wrong at runtime should be handled with an exception or normal flow control. – Dave Newton Sep 20 '13 at 01:47
  • @DaveNewton The exception approach would require an if statement around it. I think `assert`s are much more natural for this sort of thing. This is actually covered in detail in the assert [tutorial](docs.oracle.com/javase/1.4.2/docs/guide/lang/assert.html). – arshajii Sep 20 '13 at 01:49
  • @arshajii: This approach uses an exception. What if statement do I require if I'm throwing an unchecked exception? – Makoto Sep 20 '13 at 01:50
  • @Makoto I completely agree with your approach in this particular case. All I'm saying is that `assert`s have a broader use than you might think. What I mean with `if` was that `assert this_must_be_true` would have to be `if (this_must_be_true) throw ...`. The `assert` statement here is used essentially as documentation to demonstrate that its condition should always be satisfied. – arshajii Sep 20 '13 at 01:52
  • 2
    @arshajii I'm still not understanding your point. Asserts are useless when they're turned off. They're a development tool. They're not any broader than that. – Dave Newton Sep 20 '13 at 02:16
  • @DaveNewton Have you ever written a comment saying something like *"n must be even here"* to justify what you are about to do? My point is that that comment can be replaced by something like `assert n % 2 == 0`. This is definitely a matter of preference, I understand. That official tutorial I linked to asserts (no pun intended) that `assert` should be used in place of all such comments. In a nutshell, I don't agree with your statement *"Asserts are useless when they're turned off"*. – arshajii Sep 20 '13 at 02:20
  • Given the scope that `assert` was originally intended for - testing invariants, pre-conditions, and post-conditions that absolutely **had** to be true for the program to run without blowing up - if `assert` is disabled, and you have no way to propagate exceptions up the chain, then their purpose becomes effectively moot. Exceptions can serve as sufficient documentation to what happens when an invariant, pre- or post condition is invalid. – Makoto Sep 20 '13 at 02:29
  • In fact, @arshajii opinion about assertions is not a bad approach, oracle even documented its usage: http://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html – tftdias Nov 06 '15 at 11:53
8
assert object != null;
object.doSomething();

assert is used to verify the correctness of some precondition, invariant, or postcondition. In the example, we want to make sure object is not null when some method is called on it.

One thing to remember is that assert should never be executed in production code. We only make use of it when testing. There is a Java option to turn it on or off.

As for your specific example, you could use:

assert mode == 0;
assert mode == 1;

at the very beginning of the switch block to make sure only 0 and 1 are passed in.

P.S. The discussion on when to use assertion vs exception might help your understanding. The idea is that

Exceptions address the robustness of your application while assertions address the correctness of your application.

Community
  • 1
  • 1
Terry Li
  • 16,870
  • 30
  • 89
  • 134
  • 2
    @IgorGanapolsky They should not. They are a development tool. Conditionals and Exceptions do the same thing for production code. A core feature of asserts is that they ignore performance, you can use as many as needed knowing they will not affect production performance as they are compiled out. – kervin Apr 22 '15 at 17:29
4

Assertions are basically used to check something that should never happen. Some assertions use cases from http://www.javapractices.com/topic/TopicAction.do?Id=102

pre-conditions (in private methods only) - the requirements which a method requires its caller to fulfill. post-conditions - verify the promises made by a method to its caller class invariants - validate object state unreachable-at-runtime code - parts of your program which you expect to be unreachable, but which cannot be verified as such at compile-time (often else clauses and default cases in switch statements)

So the usage of assertion in your code is not correct

Rami
  • 7,162
  • 1
  • 22
  • 19