Why does eclipse say I have no return statement in this method

896 views Asked by At

I wrote a helper method for a class I am doing in java with Eclipse IDE. The code for that method is as follows

private foo getfooMonitor(String id)
{
    if(fooList.isEmpty())
    {
        if (Mgr.getValue(Name, ListPath + id) == null)
        {
            return null;
        }
    }
    else
    {
        for(foo f : fooList)
        {
            if(f.getID().equalsIgnoreCase(id))
            {
                return foo;
            }
        }
        return null;
    }
}

I am curious as to why if the method will be forced to return something, since it has an if then else block which has a return statement hit no matter what, why eclipse would think I do not have a return statement?

Is this eclipse enforcing some weird syntax because it has trouble parsing the if then else block to see the method will be forced to return, or is this a java thing with not allowing a non void method to be valid unless it has a return statement as the last line in a method body?

4

There are 4 answers

0
Brian H On BEST ANSWER

Not all paths return. If Mgr.getValue(Name, ListPath + id) == null returns false then your method doesn't have a return value

0
Turing85 On

Not each execution path has a return value: what if fooList.isEmpty(), but Mgr.getValue(Name, ListPath + id) != null ? The inner if is never entered. The outer else is ignored, because the outer if was entered. Therefore, the program reaches a state, where the method ends, but nothing is returned.

Sidenote: regarding execution path, the Java compiler is pretty dumb. Take for example the following method:

boolean isTrue(boolean value) {
    if (value) {
        return (true);
    }
    if (!value) {
        return (false);
    }
}

By the tertium non datur, either the first or the second if is executed. But this code still gives the same compile error. The only way to get this running is to change if (!value) to else (which - semantically - is the same).

0
Olivier Poulin On

you only have a return statement in the nested if statement in your original if statement. If Mgr.getValue(Name, ListPath + id) != null but outside statement is valid, then there is no return statement.

0
JustWannaFly On
private foo getfooMonitor(String id)
{
    if(fooList.isEmpty())
    {
        if (Mgr.getValue(Name, ListPath + id) == null)
        {
            return null;
        } else {
            //this path does not return a value 
        }
    }
    else
    {
        for(foo f : fooList)
        {
            if(f.getID().equalsIgnoreCase(id))
            {
                return foo;
            }
        }
        return null;
    }
}

See the path with no return indicated with a comment.