I've seen this question but have a few more questions about the usage of the assert
keyword. I was debating with a few other coders about using assert
. For this use case, there was a method that can return null if certain prerequisites are met. The code I wrote calls the method, then asserts it doesn't return null, and continues to use the returned object.
Example:
class CustomObject {
private Object object;
@Nullable
public Object getObject() {
return (object == null) ? generateObject() : object;
}
}
Now imagine I use it like this:
public void useObject(CustomObject customObject) {
object = customObject.getObject();
assert object != null;
// Do stuff using object, which would throw a NPE if object is null.
}
I was told I should remove the assert
, that they should never be used in production code, only be used in testing. Is that true?