D
D
Dmitry Bystrov2019-06-06 16:40:07
Java
Dmitry Bystrov, 2019-06-06 16:40:07

Is it necessary to check Map for null?

Good afternoon!
I have some function:

public Map<String, Object> getTestMap(MyClass myObject) {
    Map<String, Object> myResultMap = new HashMap<String, Object>();
    myResultMap.put("myKey", myObject.getMyValue());

    return myResultMap;
}

and the following line of code:
Map<String, Object> resultMap = getTestMap(myObject);

Tell me, is it worth checking resultMapfor in the future nullwhen I want to get values ​​by key?
For example like this:
Map<String, Object> resultMap = getTestMap(myObject);
if (resultMap != null) {
    Object myObject = resultMap.myKey;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AndrewStr, 2019-06-06
@Teshuhack

1. You are incorrectly extracting a value from map by key, you should use the get -> resultMap.get(myKey) method;
2. Checking for null when referring to resultMap is not needed, because you create an empty map in the getTestMap method and resultMap is never null;
3. Checking for null is needed in the getTestMap method because you call myObject.getMyValue() without checking for null, here NullPointerException can occur if the method is called with a parameter whose value is null.

D
Denis Zagaevsky, 2019-06-06
@zagayevskiy

In order to avoid such questions, I recommend marking all methods, arguments and fields with @NonNull and @Nullable.
All fields and local variables that do not change logically are final.
Declaration of variables as close as possible to the place of their use.
The answer to the question is no, in this case it is not necessary to check. But if the method is library and is not marked with an annotation - it is necessary.
It’s even better to take Kotlin and not suffer :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question