Bad idea? (sorry about the pun)

I'm putting together some simple code examples for a data structures course I'll be teaching in the fall. I wrote a trivial recursive factorial function

    static int factorial (int n)
       ...obvious code goes here

and then inserted as a new first line

      assert (n > 0);

the purpose being to introduce students to preconditions and so forth.

The little lightbulb popped up and suggested that I replace the 'assert' with an 'if' statement (see picture). Why?

Comment actions Permalink

Your code will not work if assertions are disabled, so app behavior would depend on JVM options, IDE inspection suggest to write the code that will work correctly regardless of the JVM options.

Comment actions Permalink

The code would work absolutely fine. It's just that the assertion would no longer be tested, which is the whole point of having assertions, they can be turned off after you have finished your testing (for example) and move to production.

If the expression within the 'assert' mistakenly had side effects, then I could see why you might want to (at least) warn of a problem but I feel that the suggestion that an assert should be changed to 'if' is misguided and will certainly confuse students, many of whom would just blindly go ahead and change their code, thereby missing the whole purpose of 'assert'

Is there a way to turn off suggestions JUST for that particular item? Normally, the suggestions are very valuable.

Comment actions Permalink

Much appreciated.


Please sign in to leave a comment.