I have the following code:
boolean needToAddToMap = false;
Required required;
synchronized(requiredMap)
{
if (requiredMap.containsKey(userId))
{
required = parserSetAndActionsMap.get(userId);
}
else
{
logger.warning("userId not found in map, adding now.");
needToAddToMap = true;
}
}
if (needToAddToMap)
{
required = addNewRequired(userId);
}
Later I use required but get an error, even though "required" is clearly initialized. This could be considered as a bug in the compiler, but I understand that it is computationally difficult (and even impossible) to catch all the cases.
There are several possible solutions:
Neither of these solutions sound ideal, what would be the best? any other solutions?
best practice for avoiding “variable might not have been initialized”?
Well to avoid it you have to initialize it, and I don't think setting it as null
whould cost you anything, or whould cause you anything bad, but it will surely prevent it from causing and raising this Exception.
And keep in mind that a local variable should be initialized with value before using it.
So just initialize it as null
:
Required required= null ;
So you can use it inside your if
statement.
You have to initialize it so the compiler will be happy otherwise you can just choose the best/prefered way to initialize it like this one:
Required required = null;
synchronized(requiredMap)
{
if (requiredMap.containsKey(userId))
{
required = parserSetAndActionsMap.get(userId);
}
else
{
logger.warning("userId not found in map, adding now.");
}
}
if (null == required)
{
required = addNewRequired(userId);
}
Or If you realy hate initializing to null, just avoid it with something like this:
Required required = addNewRequired(userId);;
synchronized(requiredMap)
{
if (requiredMap.containsKey(userId))
{
required = parserSetAndActionsMap.get(userId);
// remove userId from required
}
}
we end up with numerous version of this code, just choose the one that you think is the most suitable to your program requirement
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With