Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best practice for avoiding "variable might not have been initialized"

Tags:

java

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:

  1. Suppress warning (not sure is possible)
  2. Initialize to null
  3. Use the lock for longer, or use the lock twice

Neither of these solutions sound ideal, what would be the best? any other solutions?

like image 304
Clangon Avatar asked Sep 27 '22 18:09

Clangon


2 Answers

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.

like image 193
cнŝdk Avatar answered Oct 06 '22 00:10

cнŝdk


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

like image 30
jMounir Avatar answered Oct 06 '22 00:10

jMounir