What would be a better alternative to assigning a variable to null?

When I code, I often set my variables to null in order to subsequently use this information. Assigning variables to null allows me to indicate that the state of a variable is invalid, and this allows me to verify the correctness of the specified variable later in the program.

However, my static code analysis tools, such as PMD, scream when I assign the variable null, stating that it is the smell of code, and I should consider refactoring.

So my question is this: what would be the best alternative to assigning a variable to null if you want to indicate that this variable is an invalid state?

+4
source share
7 answers

. ( ) - - null. , , , null .

+1

, Java 8.

Optional<String> str = foo() // Method that returns an optional String
if(!str.isPresent()){
    // Invalid state
}else{
    String validStr = str.get();
    // Valid state
}

.of("")

+2

null empty. , String empty, , String.isEmpty(). , true false , objects . nulls. object empty. google null vs. empty, . Collections - , empty (, ):

Collections.emptyList()
Collections.emptySet()
Collections.emptyMap()

Java

Nulls

, , , null . . null , NPE, ... empty logical, . , ...

empty isEmpty(), , "" . , object .

+1

null , null : ( ) , . , ( ), .

(. Java). : https://en.wikipedia.org/wiki/Nullable_type

, PMD, , , .

+1

. null . , , var , - .

:

String str = "I AM NULL";

Int num = MIN_INT; ( , MIN_INT, ).

.

0

, , , , .

. value : "DELETED", , , . , PMD, NullPointerExceptions.

0

If you use this variable for conditional purposes, you should use a Boolean.

-1
source

All Articles