Is there a requiredFalse method in Java 8 for argument checking? - java

I want to check arguments in a method. I've found the Objects.requireNonNull method which makes the code easily readable.
Is it some similar build in solution for boolean checking?
I want a similar syntax to this:
SomeJavaObject.requiredFalse(myArgument < 0, "myArgument can not be negative!");
(I can write my own method, but I prefer using the built in java functions.)

Since we have the Apache Commons libraries in our project anyways, I tend to use the checks in the Validate class from time to time: https://commons.apache.org/proper/commons-lang/javadocs/api-3.5/org/apache/commons/lang3/Validate.html
There is similar stuff in Guava's Preconditions class, but I prefer Validate.
We decided to avoid the assert keyword because code running on a customer's machine would then have different execution paths than during local development, making it harder to debug issues.

You can use the assert keyword.
int a = -1;
assert a >= 0 : "Parameter passed to foo() can't be negative";
The code above will throw an AssertionError if you launch it with -enableassertions or -ea for short.
Caused by: java.lang.AssertionError: Parameter passed to foo() can't be negative
Keep in mind that assert by no means should be used to validate arguments passed to public methods, or even worse - user input, because they are disabled by default. Yes, they can be disabled, and this is not a pitfall of assert, but a conscious and deliberate design choice. Why you can't use that in some cases is clearly written in the official Oracle guideline:
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. Another problem with using assertions for argument checking is that erroneous arguments should result in an appropriate runtime exception (such as IllegalArgumentException, IndexOutOfBoundsException, or NullPointerException). An assertion failure will not throw an appropriate exception.
That does not mean that using assert should be avoided and is considered a bad practice. Assertion is not equal to error handling. The key is to use the right tool for the right job. Assertions are useful at catching programmers' mistakes - to make sure that something regarded as impossible indeed does never happen - for example:
Checking if a variable in a private method does not have an unexpected value, as stated in the guideline:
You can, however, use an assertion to test a nonpublic method's precondition that you believe will be true no matter what a client does with the class.
Marking a block of code that should never be reached with assert false.

There is no such method in the standard API and there are some reasons, not to add it. While Objects.requireNonNull will throw a dedicated exception, NullPointerException, there is no such obvious exception type for a method that tests an arbitrary predicate. If the predicate is testing a parameter value, an IllegalArgumentException might be appropriate, otherwise, an IllegalStateException or something completely different would fit better. You might consider an API with a Supplier for the exception, but this leads to the second issue.
If you want to support a supplier for the exception, you need a capturing lambda expression if you want to provide a message that includes the illegal value. And the overhead might be simply too much for parameter checking. The same would apply to a String parameter as it has to be constructed before invoking the utility method. This differs from the requireNonNull test where the illegal value invariably is null.
While HotSpot might be good at eliminating such overhead, the API is the standard for all JREs, including those not having such an optimization potential.
Besides that, it would make more sense to have a naming like
require(myArgument >= 0, "myArgument can not be negative!");
instead of forcing the reader to decipher a negation.
Since it’s more common to have multiple methods with similar constraints in one class, the established pattern is to have a more tailored method, e.g.
checkPositive("myArgument", myArgument);
…
private void checkPositive(String name, int arg) {
if(arg<0) throw new IllegalArgumentException(name+" is negative");
}
See for example rangeCheck in ArrayList or checkIndex in NIO Buffer

Afaik there's no such method. What I usually do is this:
if(myArgument < 0)
throw new IllegalArgumentException("myArgument must be greater or equal to 0");
(and repeat for each parameter check)
You can also use assertions, altho those aren't always welcome in production code.

Related

Difference between using assert and throwing AssetionError exception in java

To do internal logic checks, there are two ways in Java,
use the assert keyword: e.g, assert(x>y);
manually throw assertion error: e.g, if(y>x) throw new AssertionError();
What are the differences among above two methods( performance wise, programming flexibility, etc.?
Which one is considered as a good programming practice?
The main difference is that assert is not guaranteed to be processed, unless assertions are explicitly enabled (either via the -ea option to java, or programmatically). On the other hand, throwing a new AssertionError() will always work.
Some reading information: Programming with Assertions
Way #1 "assert(x>y);" uses a JVM feature which is turned off by default. However, it gives you more flexibility since you can turn it on and off as you like with one single parameter.
Way #2 "if(y>x) throw new AssertionError();" will always be executed, you can't turn it off via the assert-param. It is just an exception.
I've often seen people use Exceptions for "real" errors (network not available, wrong input provided), while assertions are often used (i.e. turned on) during development/integration for very basic checks (e.g. param not null). IMO, it's hard to draw the line.
When assert(x>y) fails, then it would raise AssertionError(provided assertions are enabled). The advantage of using java assertions is that it can be enabled or disabled during compile time. You can disable assertions for production environment which improves performance compared to raising manually AssertionError in which you always perform assertions thereby reducing performance.
Non of above answers answer my second question (Which one is considered as a good programming practice?). So I talked regards this with one of my friend and according to him, If some thing is private to the package and you are the only one calling that function (e.g, private functions) then use assert. If something is public and you expect some other third party developer may directly call the function, then do a explicit if check and throw the exception.

Guava preconditions checkNull, checkArgument

I want to check preconditions on a base class so that I know subtypes will always use constructor arguments that are valid.
Let's take as an example a constructor that:
takes 2 or more parameters
takes parameters of different types
for one parameter, it performs multiple checks (e.g. String is not null and not empty)
How would one best use the Guava preconditions approach in that case?
In a mock example like this: (this is contrived!)
protected AbstractException(String errorMessage, Throwable errorCause) {
super(errorMessage, errorCause);
checkNotNull(errorMessage,
ErrorMessage.MethodArgument.CANNOT_BE_NULL_CHECK, "errorMessage");
checkArgument(!errorMessage.isEmpty(),
ErrorMessage.MethodArgument.CANNOT_BE_EMPTY_STRING_CHECK,
"errorMessage");
checkNotNull(errorCause, ErrorMessage.MethodArgument.CANNOT_BE_NULL_CHECK,
"errorCause");
}
I end up calling super before checking the arguments because a call to super needs to be the first line of the method and, although I could do super(checkNoNull(errorMessage)), I cannot do the same wrapping using checkArgument because that returns void. So the dilemma is:
Where do I put the checks on all arguments? I don't want to create a Builder just for that
How do I "group" checks as in a fictitious checkStringNotNullAndNotEmpty()
Should I rather think about integration with matchers frameworks? (hamcrest, fest assertions...)
I use the odd-looking ErrorMessage.MethodArgument.CANNOT_BE_NULL_CHECK because the default throw does not include an error message so from the testing side I cannot recognise this as an argument validation failure rather than a "any" NPE?
Am I doing it all wrong?
This should have been a comment, but it's too long.
Calling super before the test is harmless provided that the super ctor doesn't do things which it shouldn't do anyway.
It could be prevented via a static builder method, you need no Builder. But it's not worth it.
I doubt that grouping tests is generally useful; if it was, then there would be a such method already. But if you need one such a concrete thing more than twice, then write your own; if it comes often, report it to the Guava team as an RFE.
I'm pretty sure, matchers are an overkill here as you're just creating an exception, i.e., something used only rarely (I hope). As your test is runtime only, it can't really help to catch errors. It would be nice, if you could statically ensure a "properly" constructed exception, but it's impossible in pure java.
More important: The exceptions you're throwing are probably inferior to the ones you'd get without all the checks. Imagine the user provides a cause and no message. That's bad, you think, but you replace it with an NPE lacking any cause. That's worse.
Look at Guava's Preconditions.format (package private). They could check the correct number of arguments first, but they do not. You can provide too few or too many, which is an error, but ignoring it is the best way to handle it.

Assert a good practice or not?

Is it a good practice to use Assert for function parameters to enforce their validity. I was going through the source code of Spring Framework and I noticed that they use Assert.notNull a lot. Here's an example
public static ParsedSql parseSqlStatement(String sql) {
Assert.notNull(sql, "SQL must not be null");
}
Here's Another one:
public NamedParameterJdbcTemplate(DataSource dataSource) {
Assert.notNull(dataSource,
"The [dataSource] argument cannot be null.");
this.classicJdbcTemplate = new JdbcTemplate(dataSource);
}
public NamedParameterJdbcTemplate(JdbcOperations classicJdbcTemplate) {
Assert.notNull(classicJdbcTemplate,
"JdbcTemplate must not be null");
this.classicJdbcTemplate = classicJdbcTemplate;
}
FYI, The Assert.notNull (not the assert statement) is defined in a util class as follows:
public abstract class Assert {
public static void notNull(Object object, String message) {
if (object == null) {
throw new IllegalArgumentException (message);
}
}
}
In principle, assertions are not that different from many other run-time checkings.
For example, Java bound-checks all array accesses at run-time. Does this make things a bit slower? Yes. Is it beneficial? Absolutely! As soon as out-of-bound violation occurs, an exception is thrown and the programmer is alerted to any possible bug! The behavior in other systems where array accesses are not bound-checked are A LOT MORE UNPREDICTABLE! (often with disastrous consequences!).
Assertions, whether you use library or language support, is similar in spirit. There are performance costs, but it's absolutely worth it. In fact, assertions are even more valuable because it's explicit, and it communicates higher-level concepts.
Used properly, the performance cost can be minimized and the value, both for the client (who will catch contract violations sooner rather than later) and the developers (because the contract is self-enforcing and self-documenting), is maximized.
Another way to look at it is to think of assertions as "active comments". There's no arguing that comments are useful, but they're PASSIVE; computationally they do nothing. By formulating some concepts as assertions instead of comments, they become ACTIVE. They actually must hold at run time; violations will be caught.
See also: the benefits of programming with assertions
Those asserts are library-supplied and are not the same as the built-in assert keyword.
There's a difference here: asserts do not run by default (they must be enabled with the -ea parameter), while the assertions provided by the Assert class cannot be disabled.
In my opinion (for what it's worth), this is as good a method as any for validating parameters. If you had used built-in assertions as the question title implies, I would have argued against it on the basis that necessary checks should not be removable. But this way is just shorthand for:
public static ParsedSql parseSqlStatement(String sql) {
if (sql == null)
throw new IllegalArgumentException("SQL must not be null");
...
}
... which is always good practice to do in public methods.
The built-in style of asserts is more useful for situations where a condition should always be true, or for private methods. The language guide introducing assertions has some good guidelines which are basically what I've just described.
Yes it is good practice.
In the Spring case, it is particularly important because the checks are validating property settings, etc that are typically coming from XML wiring files. In other words, they are validating the webapp's configuration. And if you ever do any serious Spring-based development, those validation checks will save you hours of debugging when you make a silly configuration mistake.
But note that there is a BIG difference between a library class called Assert and the Java assert keyword which is used to define a Java assertion. The latter form of assertions can be turned off at application launch time, and should NOT be used for argument validation checks that you always want to happen. Clearly, the Spring designers think it would be a really bad idea to turn off webapp configuration sanity checks ... and I agree.
UPDATE
In Java 7 (and later) the java.util.Objects class provides a requireNonNull convenience method to test if an argument is null and raise an exception. You use it like this:
SomeType t = ...
SomeType tChecked = Objects.requireNonNull(t);
or
SomeType tChecked = Objects.requireNonNull(t, "t should be non-null");
However, note that this method raises NullPointerException rather than IllegalArgumentException.
Based on Sun's guide on assertions, you should not use assertions for argument checking in public methods.
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.
In very large and poorly designed/maintained systems, if you're looking to improve predictability in methods that are, say, 6000 lines long and nobody in the company understands them anymore, it can be valuable to use the assert keyword to cause development environments to blow up, revealing bugs. But were you to implement those assertions in production, you might shortcircuit a patch that, though horribly conceived, fixed a problem. You want to fix that bad patch by discovering it in the dev environment, not production. So you would turn asserts on at development time, and turn them off in production.
Another valid use of the assert keyword at development time is to insert validity checks into algorithms that must execute in sub-millisecond times and are well enough insulated from unpredictable or untested callers. You may not be able to afford to preserve the validity check in production in such a case, though it's still very useful in development. On the other hand, if the source of the parameters you're validating is unpredictable or could become so (if it's determined partly by user input, for example), you can probably never afford to skip the check, even in production, and should take the performance hit as a cost of doing business. (In this last case, you probably wouldn't want to use an assert.) But you should opt for asserts to eliminate a production-time validity check only after profiling tells you you simply can't afford the overhead.
Yes it's a good idea. You're enforcing the contracting of the interface or class. If there is a contract violation you want to detect it as soon as possible. The longer you wait the more unpredictable the results can be and the harder it can be to diagnose.
When you explicitly check like this you should also provide an information message that when viewed in a log file can give useful context to help find the root cause or even just to realize you've made a wrong assumption about what the contract is.
I'm keeping my assertions in released binaries but with modified behavior: abort is not called but stacktrace is collected.
More details here: http://blog.aplikacja.info/2011/10/assert-to-abort-or-not-to-abort-thats-the-question/

Some (anti-)patterns on using assert (Java, and others)

Finally, I have a question to ask on Stack Overflow! :-)
The main target is for Java but I believe it is mostly language agnostic: if you don't have native assert, you can always simulate it.
I work for a company selling a suite of softwares written in Java. The code is old, dating back to Java 1.3 at least, and at some places, it shows... That's a large code base, some 2 millions of lines, so we can't refactor it all at once.
Recently, we switched the latest versions from Java 1.4 syntax and JVM to Java 1.6, making conservative use of some new features like assert (we used to use a DEBUG.ASSERT macro -- I know assert has been introduced in 1.4 but we didn't used it before), generics (only typed collections), foreach loop, enums, etc.
I am still a bit green about the use of assert, although I have read a couple of articles on the topic. Yet, some usages I see leave me perplex, hurting my common sense... ^_^ So I thought I should ask some questions, to see if I am right to want to correct stuff, or if it goes against common practices. I am wordy, so I bolded the questions, for those liking to skim stuff.
For reference, I have searched assert java in SO and found some interesting threads, but apparently no exact duplicate.
How to avoid “!= null” statements in java? and How much null checking is enough? are quite relevant, because lot of asserts we have just check if variable is null. At some places in our code, there are usages of the null object (eg. returning new String[0]) but not always. We have to live with that, at least for maintenance of legacy code.
Some good answers also in Java assertions underused.
Oh, and SO indicates with reason that When should I use Debug.Assert()? question is related too (nice feature to reduce duplicates!).
First, main issue, which triggered my question today:
SubDocument aSubDoc = documents.GetAt( i );
assert( aSubDoc != null );
if ( aSubDoc.GetType() == GIS_DOC )
{
continue;
}
assert( aSubDoc.GetDoc() != null );
ContentsInfo ci = (ContentsInfo) aSubDoc.GetDoc();
(Yes, we use MS' C/C++ style/code conventions. And I even like it (coming from same background)! So sue us.)
First, the assert() form comes from conversion of DEBUG.ASSERT() calls. I dislike the extra parentheses, since assert is a language construct, not (no longer, here) a function call. I dislike also return (foo); :-)
Next, the asserts don't test here for invariants, they are rather used as guards against bad values. But as I understand it, they are useless here: the assert will throw an exception, not even documented with a companion string, and only if assertions are enabled. So if we have -ea option, we just have an assertion thrown instead of the regular NullPointerException one. That doesn't look like a paramount advantage, since we catch unchecked exceptions at highest level anyway.
Am I right supposing we can get rid of them and live with that (ie. let Java raise such unckecked exception)? (or, of course, test against null value if likely, which is done in other places).
Side note: should I have to assert in the above snippet, I would do that against ci value, not against the getter: even if most getters are optimized/inlined, we cannot be sure, so we should avoid calling it twice.
Somebody told, in the last referenced thread, that public methods should use tests against values of parameters (usage of the public API) and private methods should rely on asserts instead. Good advice.
Now, both kinds of methods must check another source of data: external input. Ie. data coming from user, from a database, from some file or from the network, for example.
In our code, I see asserts against these values. I always change these to real test, so they act even with assertions disabled: these are not invariants and must be properly handled.
I see only one possible exception, where input is supposed constant, for example a database table filled with constants used in relations: program would break if this table is changed but corresponding code wasn't updated.
Do you see other exceptions?
Another relatively frequent use I see, which seems OK: in the default of a switch, or at the end of a series of else if testing all possible values (these cases date back before our use of enums!), there is often an assert false : "Unexpected value for stuff: " + stuff;
Looks legitimate for me (these cases shouldn't happen in production), what do you think? (beyond the "no switch, use OO" advices which are irrelevant here).
And finally, are there any other useful use cases or annoying gotchas I missed here? (probably!)
The number one rule is to avoid side-effects in assertions. In other words, the code should behave identically with assertions turned off as it does when assertions are turned on and not failing (obviously assertions that fail are going to alter the behaviour because they will raise an error).
The number two rule is not to use assertions for essential checks. They can be turned off (or, more correctly, not turned on). For parameter-checking of non-private methods use IllegalArgumentException.
Assertions are executable assumptions. I use assertions to state my beliefs about the current state of the program. For example, things like "I assume that n is positive here", or "I assume that the list has precisely one element here".
I use assert, not only for parameter validation, but also used for verifying Threads.
Every time I do swing, I write assert in almost every method to mark "I should only be execute in worker thread/AWTThread". (I think Sun should do it for us.) Because of the Swing threading model, it MAY NOT fail (and randomly fail) if you access swing api from non-UI thread. It is quite difficult to find out all these problem without assert.
Another example I can imagination is to check JAR enclosed resource. You can have english exception rather then NPE.
EDIT:
Another example; object lock checking. If I know that I am going to use nested synchronized block, or when I am going to fix a deadlock, I use Thread.holdLock(Object) to ensure I won't get the locks in reverse order.
EDIT(2): If you are quite sure some code block should never be reach, you may write
throw new AssertionError("You dead");
rather then
assert false:"I am lucky";
For example, if you override "equals(Object)" on a mutable object, override hashCode() with AssertionError if you believe it will never be the key. This practice is suggested in some books. I won't hurt performance (as it should never reach).
you have touched on many of the reasons why i think asserts should be avoided in general. unless you are working with a codebase where assert usage has very strict guidelines, you very quickly get into a situation where you cannot ever turn the assertions off, in which case you might as well just be using normal logic tests.
so, my recommendation is skip the assertions. don't stick in extra null-pointer checks where the language will do it for you. however, if the pointer may not be dereferenced for a while, up-front null checking is a good idea. also, always use real exceptions for cases which should "never" happen (the final if branch or the default switch case), don't use "assert false". if you use an assertion, there's a chance someone could turn it off, and if the situation actually happens, things will get really confused.
I recommend checking parameters in public (API) methods and throwing IllegalArgumentException if the params aren't valid. No asserts here as an API user requires to get a proper error (message).
Asserts should be used in non-public methods to check post-conditions and possibly pre-conditions. For example:
List returnListOfSize(int size) {
// complex list creation
assert list.size == size;
}
Often using a clever error handling strategy asserts can be circumvented.

How to show if a method may return null

After posting this question and reading that one I realized that it is very important to know if a method is supposed to return null, or if this is considered an error condition and an exceptions should be thrown. There also is a nice discussion when to return ‘null’ or throw exception .
I'm writing a method and I already know if I want to return null or throw an exception, what is the best way to express my decision, in other words, to document my contract?
Some ways I can think of:
Write it down in the specs / the documentation (will anyone read it?)
Make it part of the method name (as I suggested here)
assume that every method that throws an exception will not return null, and every one that does 'not' throw might return null.
I'm mainly talking about java, but it might apply to other languages, too: Why is there a formal way to express if exceptions will be thrown (the throws keywords) but no formal way to express if null might be returned?
Why isn't there something like that:
public notnull Object methodWhichCannotReturnNull(int i) throws Exception
{
return null; // this would lead to a compiler error!
}
Summary and Conclusion
There are many ways to express the contract:
If your IDE supports it (as IntelliJ), it's best to use an annotation like #NotNull because it is visible to the programmer and can be used for automated compile time checking. There's a plugin for Eclipse to add support for these, but it didn't work for me.
If these are not an option, use custom Types like Option<T> or NotNull<T>, which add clarity and at least runtime checking.
In any way, documenting the contract in the JavaDoc never hurts and sometimes even helps.
Using method names to document the nullability of the return value was not proposed by anyone but me, and though it might be very verbose und not always useful, I still believe sometimes it has its advantages, too.
A very good follow up question. I consider null a truly special value, and if a method may return null it must clearly document in the Javadoc when it does (#return some value ..., or null if ...). When coding I'm defensive, and assume a method may return null unless I'm convinced it can't (e.g., because the Javadoc said so.)
People realized that this is an issue, and a proposed solution is to use annotations to state the intention in a way it can be checked automatically. See JSR 305: Annotations for Software Defect Detection, JSR 308: Annotations on Java Types and JetBrain's Nullable How-To.
Your example might look like this, and refused by the IDE, the compiler or other code analysis tools.
#NotNull
public Object methodWhichCannotReturnNull(int i) throws Exception
{
return null; // this would lead to a compiler error!
}
You can use the Option type, which is very much like a list that has zero or one element. A return type of Option<Object> indicates that the method may return an Object, or it may return a special value of type None. This type is a replacement for the use of null with better type checks.
Example:
public Option<Integer> parseInt(String s) {
try {
return Option.some(Integer.parseInt(s));
}
catch (Exception e) {
return Option.none();
}
}
If you use this consistently, you can turn on IDE null-warnings, or just use grep for null which should not appear in your code at all if you use Option.none() everywhere you would normaly use a null literal.
Option comes standard with Scala, and it is called Maybe in Haskell. The link above is to a library called Functional Java that includes it. That version implements the Iterable interface, and has monadic methods that let you compose things nicely. For example, to provide a default value of 0 in case of None:
int x = optionalInt.orSome(0);
And you can replace this...
if (myString != null && !"".equals(myString))
...with this, if you have an Option<String>...
for (String s : myOptionString)
There's some support for a #Nullable and #NotNull annotation in IntelliJ IDEA. There's also some talk about adding those annotations (or a similar feature) to Java 7. Unfortunately I don't know how far that got or if it's still on track at all.
Indeed: in our framework we have a 'non-null' pointer type, which may be returned to indicate that the method will always return a value.
I see three options:
wait for language support to express it (e.g. the C# ?! thing)
use Aspect Orientation to build your own language extensions to express it
use a custom type to express it
(but builds on developer cooperation) use a naming scheme to indicate it
For Java, one can use the Javadoc description of a method to document the meaning of the returned value, including whether it can be null. As has been mentioned, annotations may also provide assistance here.
On the other hand, I admit that I don't see null as something to be feared. There are situations in which "nobody's home" is a meaningful condition (although the Null Object technique also has real value here).
It is certainly true that attempting a method invocation on a null value will cause an exception. But so will attempting to divide by zero. That doesn't mean that we need to go on a campaign to eliminate zeroes! It just means that we need to understand the contract on a method and do the right thing with the values that it returns.
Have you had a look at Spec#?
You could write your own annotation (Java) or attribute (C#) to indicate that the return value might be null. Nothing will automatically check it (although .NET 4.0 will have code contracts for this sort of thing) but it would at least act as documentation.
Maybe you could define a generic class named "NotNull", so that your method might be like:
public NotNull<Object> methodWhichCannotReturnNull(int i) throws Exception
{
// the following would lead to a run-time error thown by the
// NotNull constructor, if it's constructed with a null value
return new NotNull<Object>(null);
}
This is still a run-time (not a compile-time) check, but:
It's thrown in the implementation of the method (it's not a fault in the calling code)
It's self-documenting (the caller knows he's geting NotNull<T> as a return type)
At all costs, avoid relying on the JavaDocs. People only read them if the signature doesn't appear trivial and self-explanatory (Which is bad to begin with), and these who actually bother to read them are less likely to make a mistake with the nulls since they are currently being more careful.
If you're using Java 5+, you can use a custom Annotation, e.g. #MayReturnNull
UPDATE
All coding philosophy aside (returning null, using exceptions, assertions, yada yada), I hope the above answers your question. Apart from primitives having default values, complex types may or may not be null, and your code needs to deal with it.
Generally speaking, I would assume that a null return value is against the contract of the API by default. It is almost always possible to design your code such that a null value is never returned from your APIs during "normal" flow of execution. (For example, check foo.contains(obj) rather then calling foo.get(obj) and having a separate branch for null. Or, use the Null object pattern.
If you cannot design your API in such a way, I would clearly document when and why a null could be thrown--at least in the Javadoc, and possibly also using a custom #annotation such as several of the other answers have suggested.

Categories