SonarQube warning about NPE even though null check is done - nullpointerexception

Why does Sq keep saying that the lines:
bankIdAuthenticationEntity.setOrderReference(authResponse.getBody().getOrderRef());
bankIdAuthenticationEntity.setAutoStartToken(authResponse.getBody().getAutoStartToken());
Can cause a NPE even after i check for it?

There are 2 cases:
1st case: If getBody() method may return different (including null) results on consecutive calls then it may cause NPE.
Try to extract the result of the first call into a variable like this:
final BodyClass body = authResponse.getBody();
if(body != null) {
bankIdAuthenticationEntity.setOrderReference(body.getOrderRef());
bankIdAuthenticationEntity.setAutoStartToken(body.getAutoStartToken());
} else {
// ...
}
2nd case is (mentioned in a comment by Luke Woodward) that both methods getOrderRef() and getAutoStartToken() may returned Integer/Long/Character which may be null.
Then they need to be unboxed into int/long/char by the setOrderReference(...) and setAutoStartToken(...) methods which may cause NPE.

Related

I'm unable to remove my NullPointerException error

The below code
fun main(args: Array<String>) {
println("Enter your value : ")
try{
val(a, b, c) = readLine()!!.split(' ')
println("Values are $a $b and $c")
}catch(ex : IndexOutOfBoundsException){
println("Invalid. Missing values")
}
}
produces the following error in Kotlin Playground:
Enter your value:
Exception in thread "main" kotlin.KotlinNullPointerException at FileKt.main(File.kt:4)
I have seen other questions with NullPointerException but I am unable to resolve it. I might would have missed some so it would be really helpful if you can share useful links. Since I am new to Kotlin, it would be awesome if you correct my program.
Remark: I don't have any background on java either and most of the NullPointerException questions are based on java
Edit 1 : I have tried gidds' solution and it seems to be working except one minor fault. The readLine() is for some reason not working.
The below code
fun main(args : Array <String>){
val line = readLine()
try{
println("Output : $line")
if (line != null) {
val(a, b, c) = line.split(' ')
println("Values are $a $b and $c")
} else {
println("No values given...")
}
}
catch(ex : IndexOutOfBoundsException){
println("Invalid. Missing Values...")
}
}
produces the following error in Kotlin Playground :
Output : null
No values given...
I guess I was getting the previous errors due to the same reason, i.e. readLine() was not working properly and the user is not getting an opportunity to give input(s).
With readLine()!!, you are saying the compiler that if this returns null, that will crash with NullPointerException. In another way, you must be sure to have return value of readLine() to be not null. Read more about !! operator here.
The not-null assertion operator (!!) converts any value to a non-null
type and throws an exception if the value is null.
You can have null check with elvis operator like below:
try{
val(a, b, c) = readLine()?.split(' ')
println("Values are $a $b and $c")
}catch(ex : IndexOutOfBoundsException){
println("Invalid. Missing values")
}
To expand on the earlier answer, this is about how to handle nulls.
The problem is that readLine() can return null.  (This happens if end-of-file is reached; for example, if you redirect the input from a file, and reach the end of the file; or if it's taking input from the keyboard and you press Ctrl+D.)
The Kotlin compiler knows this.  (Nullability is built into Kotlin's type system.  readLine() returns a String? — the question mark indicates that the value could be null.)
Kotlin is very careful about null-safety, and won't let you do anything with the value that would fail if it's null.  So in your code, if you omit the !!, you get an error on the following ..  (‘Only safe (?.) or non-null asserted (!!.) calls are allowed on a non-nullable receiver of type String?’)
So you have to handle the null somehow.
Appending the not-null assertion !! effectively promises the compiler that you know better, and that it can never be null.  This is usually a bad idea (which is why that operator was designed to look ugly); in practice, you generally don't know better than the compiler, and it will trip you up — as you've discovered!  In your case readLine() did return null, and so the !! operator threw a KotlinNullPointerException.
So, you need a better way to handle it.
The traditional way is an explicit check, e.g.:
val line = readLine()
if (line != null) {
// Within this block, the compiler knows that line
// cannot be null.
} else {
println("No values given.")
}
This is a good, clear, general approach.  And it may be the best approach in your case.  (You'd still need to catch the IndexOutOfBoundsException, though.)
Because that approach can be a bit long-winded, Kotlin has some other tools that can be better in particular situations.  I don't think any are appropriate here, but I'll mention some for completeness:
One of those is the safe-call operator ?. given in the error message and the earlier answer.  This makes the call only if the value is not null; otherwise, it returns the null directly.  That can be really useful, but it's not a simple answer in this case, as your comment shows: although it avoids trying to split() the null, you then fail to deconstruct it into the three values a, b, and c.  (After all, null is not an array.)
If you wanted to substitute default values for a, b, and c if there was no input, you could use the safe-call operator in conjunction with the elvis operator ?:.  That returns the left-hand side if it's not null, else the right-hand side.  So you could do e.g.:
val (a, b, c) = readLine()?.split(' ')
?: arrayOf("defA", "defB", "defC")
println("Values are $a, $b, and $c.")
In this case, if readLine() returns a string, split() would be called on it; or if not, it would use the hard-coded array instead.
Note that this still isn't a complete solution, as it won't cope if you enter a line with less than two spaces.  (So you'd still need to catch the IndexOutOfBoundsException, or check for that case explicitly.)
(Perhaps the shortest solution overall would be to leave the !! intact, and change the catch block to catch Exception, so it would catch the KotlinNullPointerException along with the IndexOutOfBoundsException.  I'm not recommending that, as it's ugly: it's not clear to anyone reading the code what could happen and what exceptions you're intending to catch — and it could hide other problems in the code if they also resulted in exceptions.)

What is the difference between not-null checks in Kotlin?

There are some ways to fulfill a null-checking in Kotlin:
1.
if(myVar != null) {
foo(myVar)
}
2.
myVar?.let {
foo(it)
}
3.
myVar?.run {
foo(this)
}
What are the difference between these ways?
Are there any reasons (performance, best practice, code style etc.) why I should prefer on way over the other?
!! is to tell the compiler that I am sure the value of the variable is not null, and if it is null throw a null pointer exception (NPE) where as ?. is to tell the compiler that I am not sure if the value of the variable is null or not, if it is null do not throw any null pointer.
Another way of using a nullable property is safe call operator ?.
This calls the method if the property is not null or returns null if that property is null without throwing an NPE (null pointer exception).
nullableVariable?.someMethodCall()
All three code are behave same null check in operation-wise.
?. is used for chain operations.
bob?.department?.head?.name // if any of the properties in it is null it returns null
To perform a chain operation only for non-null values, you can use the safe call operator together with let
myVar?.let {
foo(it)
}
the above code is good for code style and performance
more details refer Null Safety
The ways 2 and 3 are more idiomatic for Kotlin. Both functions are quite similar. There is little difference with argument passing.
For example, we have a nullable variable:
var canBeNull: String? = null
When you working with T.run you work with extension function calling and you pass this in the closure.
canBeNull?.run {
println(length) // `this` could be omitted
}
When you call T.let you can use it like lambda argument it.
canBeNull?.let {
myString -> println(myString.length) // You could convert `it` to some other name
}
A good article about Kotlin standard functions.
All three are roughly equivalent.
The if case is more like most other languages, and so many developers may find it easier to read.
However, one difference is that the if case will read the value of myVar twice: once for the check, and again when passing it to foo(). That makes a difference, because if myVar is a property (i.e. something that could potentially be changed by another thread), then the compiler will warn that it could have been set to null after the check. If that's a problem (e.g. because foo() expects a non-null parameter), then you'll need to use one of the other cases.
For that reason, the let case has become fairly common practice in Kotlin. (The run case does just about the same thing, but for some reason isn't as popular for this sort of thing. I don't know why.)
Another way around it is to assign myVar to a temporary value, test that, and then use that. That's also more like other languages, but it's more verbose; many people prefer the conciseness of the let case — especially when myVar is actually a complicated expression.
The examples in your question don't show the true reason to decide.
First of all, since you're not using the return value of foo, you should use neither let nor run. Your choice is between also and apply.
Second, since you already have the result you want to null-check in a variable, the difference fades. This is a better motivating example:
complexCall(calculateArg1(), calculateArg2())?.also {
results.add(it)
}
as opposed to
val result = complexCall(calculateArg1(), calculateArg2())
if (result != null) {
results.add(result)
}
The second example declares an identifier, result, which is now available to the rest of the lexical scope, even though you're done with it in just one line.
The first example, on the other hand, keeps everything self-contained and when you go on reading the rest of the code, you are 100% confident that you don't have to keep in mind the meaning of result.
Kotlin have new features with NullPoint-Exception as Compare to Java.
Basically When we do Coding in Java , then we have to Check with !! in every Flied.
But in Kotlin, it is Easy way to Implement First
as Like,
Suppose, in Kotlin
var response:Json?=Null
response:Json?.let {
this part will handle automatic if response is Not Null....then this Block start Executing }?.run {
This is Nullable But, where we Can put Warring } So, I am Suggest you Guys to Start Work in Kotlin with this Features Provided by Kotlin.
(Flied)?.let { Not Null Value Comes Under }?.run{ Null Value Code }
This will Handle to NullPoint Exception or Protect You App for Crash
What you want to achieve
What you want to achieve is that the Kotlin compiler does a smart cast on the variable you are working with.
In all of your three examples, the compiler can do that.
Example:
if(myVar != null) {
foo(myVar) // smart cast: the compiler knows, that myVar can never be null here
}
The choice
Which one of the options to use, is really a matter of style. What you should not do is mix it up to often. Use one and stick to it.
You don't need to worry about performance since let and run are inlined (see inline function). This means that their code (body) is copied to the call site at compile time so there is no runtime overhead.

When working with Java libraries in Kotlin, is it more idiomatic to use ? or !! on method return values?

I'm new to Kotlin and there's a common pattern that I'm not sure how to deal with most correctly. Take this code, for example, which doesn't compile:
git_repo?.add().addFilepattern()
add() is a call in the JGit library which is purely Java, so its return type is AddCommand!.
I have two options:
git_repo?.add()!!.addFilepattern("test.txt")
and
git_repo?.add()?.addFilepattern("test.txt")
Both work fine and given that
I don't know the intricacies of the library implementation,
the documentation of the JGit library doesn't specify whether add() can return null, and
within this context I'd typically expect add() to not return a null
Which version is more idiomatically correct to write in Kotlin? It seems that this would be a fairly common issue to deal with since basically every non-Kotlin library would introduce this issue.
I would use the ?. safe operator and then put your own exception at the end after an ?: Elvis operator. This way you get a message that is meaningful. Using just !! isn't a very helpful message to someone down the road who has no idea what the intricacies were either.
val cmd = gitRepo.add()?.addFilepattern("test.txt") ?: throw IllegalStateException("assert: gitRepo.add() returned an unexpected null")
cmd.doSomething() // never is null guaranteed
If the value is every null you will have a custom error.
assert: gitRepo.add() returned an unexpected null
And after this line, you will not have to null check because the result of the expression is guaranteed never to be null.
If you inspect the code of the other library and ensure it would never ever be null no matter what, then a !! is appropriate. But if not sure, do one better with the custom message.
Note I dropped the first ?. from your example because I'm assuming git_repo itself is not nullable. Plus I renamed it not to have an underscore which isn't normal Kotlin naming convention.
If you are sure that git_repo will always return a value!! is fine in that case.
It is ugly but !! will always be there when you use Java libraries, and you can't avoid it.
The only reason i would use git_repo?.add()?.addFilepattern("test.txt"), would be if you are returning a value, and you want the value to be nullable so that your calling method can handle the nullable.
fun nullableMethod(): string? {
return git_repo?.add()?.addFilepattern("test.txt")
}
fun callingMethod() {
if(this.nullableMethod() != null) {
}
//Else
}
If you are guaranteed it is never going to null, use !!

Code contracts - Assume vs Requires

What's the diference between these two statements ?
Contract.Requires(string.IsNullOrWhiteSpace(userName));
Contract.Assume(string.IsNullOrWhiteSpace(userName));
Imagine you have a method like this:
bool ContainsAnX(string s)
{
return s.Contains("X");
}
Now, this method will always fail if you pass null to it, so you want to ensure this never happens. This is what Contract.Requires is for. It sets a precondition for the method, which must be true in order for the method to run correctly. In this case we would have:
bool ContainsAnX(string s)
{
Contract.Requires(s != null);
return s.Contains("X");
}
(Note: Requires and Ensures must always be at the start of a method, as they are information about the method as a whole. Assume is used in the code itself, as it is information about that point in the code.)
Now, in your code that calls the method "ContainsAnX", you must ensure that the string is not null. Your method might look like this:
void DoSomething()
{
var example = "hello world";
if (ContainsAnX(example))
Console.WriteLine("The string contains an 'X'.");
else
Console.WriteLine("The string does not contain an 'X'.");
}
This will work fine, and the static checker can prove that example is not null.
However, you might be calling into external libraries, which don't have any information about the values they return (i.e. they don't use Code Contracts). Let's change the example:
void DoSomething()
{
var example = OtherLibrary.FetchString();
if (ContainsAnX(example))
Console.WriteLine("The string contains an 'X'.");
else
Console.WriteLine("The string does not contain an 'X'.");
}
If the OtherLibrary doesn't use Code Contracts, the static checker will complain that example might be null.
Maybe their documentation for the library says that the method will never return null (or should never!). In this case, we know more than the static checker does, so we can tell it to Assume that the variable will never be null:
void DoSomething()
{
var example = OtherLibrary.FetchString();
Contract.Assume(example != null);
if (ContainsAnX(example))
Console.WriteLine("The string contains an 'X'.");
else
Console.WriteLine("The string does not contain an 'X'.");
}
Now this will be okay with the static checker. If you have runtime contracts enabled, the Assume will also be checked at run time.
Another case where you might need Assume is when your preconditions are very complex and the static checker is having a hard time proving them. In this case you can give it a bit of a nudge to help it along :)
In terms of runtime behavior there won't be much difference between using Assume and Requires. However, results with the static checker will differ greatly. The meaning of each is different as well, in terms of who is responsible for the error in case of failure:
Requires means that the code which calls this method must ensure the condition holds.
Assume means that this method is making an assumption which should always hold true.
It only differs design-time/static-analysis-time
Contract.Assume:
"Instructs code analysis tools to assume that the specified condition is true, even if it cannot be statically proven to always be true"
And:
At run time, using this method is equivalent to using the Assert(Boolean) method.
Contract.Requires will guarantee that the given predicate is true and static code analyzers might raise an error if they can't 'prove' that is not the case. On Contract.Assume the static analyzer will continue/issue a warning/whatever the tool will decide.
According to official documentation: pages 7 (preconditions) and 11 (assumes).
Requires:
Is a precondition ("preconditions are extressed by using Contract.Requires");
As a precondition will be executed on method invoke;
Assumes:
Not a precondition, not a postcondition, not an invariant;
Is executed at the point where it is specified;
p. 11 "Exist in a build only when the full-contract symbol or DEBUG symbol is defined";

How to return often occurring error in object oriented environment?

assume you have a function that polls some kind of queue and blocks for a certain amount of time. If this time has passed without something showing up on the queue, some indication of the timeout should be delivered to the caller, otherwise the something that showed up should be returned.
Now you could write something like:
class Queue
{
Thing GetThing();
}
and throw an exception in case of a timeout. Or you
write
class Queue
{
int GetThing(Thing& t);
}
and return an error code for success and timeout.
However, drawback of solution 1 is that the on a not so busy queue timeout is not an exceptional case, but rather common. And solution 2 uses return values for errors and ugly syntax, since you can end up with a Thing that contains nothing.
Is there another (smart) solution for that problem? What is the preferred solution in an object oriented environment?
I would use exceptions only when the error is serious enough to stop the execution of the application, or of any big-enough application's component. But I wouldn't use exceptions for common cases, after which we continue the normal execution or execute the same function again. This would be just using exceptions for flow control, which is wrong.
So, I suggest you to either use the second solution that you proposed, or to do the following:
class Queue
{
bool GetThing(Thing& t); // true on success, false on failure
string GetLastError();
};
Of course you can stick with an int for an error code, instead of a string for the full error message. Or even better, just define class Error and have GetLastError() return it.
Why not just return null from GetThing in your first solution, changing it to return a Thing *? It seems to fit the bill, at least from the information you've given so far.
In the first, and second case, you can't do anything but throw an exception. When you return a Thing, or a Thing&, you don't have the option of not returning a Thing.
If you want to fail without using an exception then you need:
class Queue
{
// Either something like this. GetThing retuns NULL on an error,
// GetError returns a specific error code
Thing* GetThing();
int GetError();
// This kind of pattern is common. Return a result code
// and set ppOut to a valid thing or NULL.
int GetThing(Thing** ppOut);
};