Is it good practice to use assert in Java?
Asked Answered
D

11

34

I know that the keyword assert exists in java. However I don't remember seeing code that uses it. Probably I am using exceptions and logging in places where I could have used it. Is it a good practice to use the assert keyword in java?

EDIT: I know that assertions in general is a good practice. my question is, to be more accurate, if in java the BKM of assertion is using the assert keyword rather than using exception, logging and other techniques.

Docilu answered 27/12, 2010 at 9:6 Comment(0)
K
29

The main reason assertions are not used is because they are not enabled by default. Therefore if you have a condition that is important enough to require an assertion you can't rely on assertions being enabled to get the job done.

As other answers have correctly stated they're designed for development-time testing and debugging because they cost nothing if assertions are disabled in production. I think it's better to create explicit tests in your testing framework (e.g. a unit test for edge conditions) than rely on someone enabling assertions while testing.

However a good example I've seen for using assertions is checking private method arguments. Since you control the access to those methods you can check that your own class is using the method correctly while your public methods use more reliable argument checking techniques (annotations, if statements, 3rd-party libraries, etc). That way even if assertions are disabled your method should be protected but developers looking at the source code can see the preconditions for your method and turn assertions on for an extra safety net when working on that class.

Kirkland answered 27/12, 2010 at 10:31 Comment(3)
"not enabled by default" a little bit confusing. For standalone java application the contributor could switch it on/off free. For managed environments (JEE, servers) it sometimes switched on by default - SAP Cloud Platform for integration by example uses Java asserts with Groovy fancy outputs.Serra
This is a really bad reason to define assertions bad. Assertions are supposed to be tested during development to catch coding bugs as soon as possible. I.e. there is no way to recover because the program is wrong. An assertion going off in runtime is game over, you need a new deployment.Mckinleymckinney
i feel like "assert" is just a dude trying to stick himself somewhere to be useful but can't find a place where he belongsSpiller
C
22

I used assertions a lot more when I wrote in C++ than I do in Java. I don't use them as much because I don't need them as often anymore. Many of the C++ bugs I would try to catch with assertions are no longer a problem in Java.

Having said that, assertions are very valuable, but many people don't use them much partly because they don't understand them. I've heard people complain that they throw an Error instead of an Exception. I've also heard this question: Why don't you just use an exception and handle the case instead of using an assert?

My reply to both is the same. Assertions aren't supposed to catch cases that you expect to see in a working application. The purpose of assertions are to catch bugs. You should only use them where the only way to "handle" them is to go back and fix the code. That's why they don't throw exceptions -- You don't want them to be part of your general exception handling.

As for turning them on, my IDE is set to turn them on by default. So, for my internal testing, I always know they're on.

Here's an example where an assert is the only thing to use: I worked on a big Swing project where the original coders didn't understand that the UI can only be updated from the event thread, which led to all sorts of bugs. So I put in this assert in a lot of places where things were behaving funny: assert EventQueue.isDispatchThread(); If this assertion got fired, we were running from the wrong thread, and the developers needed to be notified so they could move the code to the proper thread. There's no way good to handle this in a working application.

Chemmy answered 7/4, 2012 at 4:40 Comment(1)
There is no such thing as a situation where the only way to "handle" a failed execution is to go back and fix the code.Skellum
S
9

Yes it's weird. The feature was highly requested, yet after it's introduced into the language, practically nobody uses it.

I sometimes use assert as a commenting tool. Instead of

// now it should be empty

I may write

assert size == 0;

But I don't really turned on assert, so the assertion was never tested.

It's possible that people prefer to test the code from outside, and they don't feel the need to plant many asserts in the code flow.

Spectral answered 27/12, 2010 at 10:35 Comment(1)
You don't need to turn asserts on. They are enabled when tests are run (IDE, Maven, etc.). So, they still serve as both commenting tool and verification - just ensure that tests reach this code.Frilling
S
5

Yes it is a very good practice to assert your assumptions. Read Design By Contract. assert can be used to verify pre conditions, invariants and post conditions during integration and testing phases. This helps to catch the errors while in development and testing phases. And you can safely turn it off in production to avoid performance issues.

assert's are normally used to check the correctness of your internal method logic or enforcing the contract within a given class. But use exceptions to make the contract explicit.

Sentimental answered 27/12, 2010 at 9:18 Comment(0)
J
2

Assert isn't used very much these days. It can be useful in performance critical applications during development to weed out all the bugs and then simply disabling assertions via switches.

Disabling assertions at runtime is the primary benefit, since, when disabled, they use up basically zero resources.

A more "modern" approach is, for example, using Google Guava with Preconditions. This is a library type assertion mechanism that you can use when conditions must be met and you don't want to fumble around with java switches.

Jospeh answered 27/12, 2010 at 9:16 Comment(1)
As for Guava, the linked docs state: "Precondition exceptions [...] are used to signal that the calling method has made an error. [...] Postcondition or other invariant failures should not throw these types of exceptions." which IMO doesn't make them a replacement for asserts() used for invariants about the code.Unni
P
1

Well, it really depends on how you look at it, but, it is recommended.

For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light.

Payola answered 27/12, 2010 at 9:14 Comment(0)
I
1

in my algortihms lectures, my lecturer always maintained the usefulness of assertions. theyre mostly used for test and debugging purposes, which my be why u do see code using it. but yes, theyre highly recomended. they can be disabled if you're worried abt performance. normally i use System.out.println or breakpoints to test, but assertions are one way too. here's what i mean:

For example, to prove that sort+reverse is equivalent to sort in reverse order:
Method 1: sort(int[] arr, int len)
// pre: len is the length of the array arr
// post: arr is sorted in ascending order
Method 2: reverse(int[] arr)
// post: the order of elements in arr is
// reversed (e.g. [9 5 10] -> [10 5 9])
Assertion 1: the length of arr is len
sort(arr,len);
Assertion 2: arr is sorted in ascending order
reverse(arr);
Assertion 3: the order of arr is reversed
Iodine answered 27/12, 2010 at 9:18 Comment(0)
S
1

I was very pleased when used assertions in my java application and sqlite-jdbc returned some smart assertion for one case.

So if you turn on assertions, they could appear in some third-party library.

Serra answered 30/6, 2015 at 17:45 Comment(1)
They can be turned on for a specific package prefix.Mckinleymckinney
M
0

Yes. It is a way to validate that some "must" conditions are met. Note that you have to explicitly enable assertions.

Otherwise you can use Validate from commons-lang. You just write Validate.notNull(foo) and it throws an exception if foo is null.

Magnificence answered 27/12, 2010 at 9:15 Comment(0)
A
0

It is beneficial for short conditions. However, use depends upon your coding practices. Because, sometimes the logic can better be applied using "assert" then using tough methods !

Assumption answered 27/12, 2010 at 9:22 Comment(0)
S
0

The main reason assertions are not used is because they are not enabled by default. Therefore if you have a condition that is important enough to require an assertion you can't rely on assertions being enabled to get the job done.

I agree that the big design mistake of assertions is that they are disabled by default.

Therefore I put

static { AssertionUtil.enableAssertionsForThisClass(); }

at the top of every class. See http://commons.unkrig.de .

Susurrant answered 24/3, 2016 at 8:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.