Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a method in eclipse doesn't seem to work

I try to do a simple refactoring (extract method) in eclipse. I select the following code block and do a alt+shift+M (shortcut for extracting).

    Parser parser = Parser.createParser(comment.getText(), "UTF-8");
    NodeList htmlAnchorNodes = null;
    try {
        htmlAnchorNodes = parser
                .extractAllNodesThatMatch(new TagNameFilter("a"));
    } catch (ParserException e) {
        e.printStackTrace();
    }

    int size = htmlAnchorNodes.size();

Only the size variable is used afterwards.

I get the error message:

Ambiguous return value: Selected block contains more than one assignment to local variables. Affected variables are:

NodeList htmlAnchorNodes

Parser parser

int size

How can I get Eclipse to recognize the return value?

like image 491
user1769255 Avatar asked Oct 05 '22 17:10

user1769255


1 Answers

In some cases Eclipse isn't sure which variable you intend to return. It would be ideal if it would prompt you to select one, or do an analysis based on which value is actually used later, but I've worked around it by using braces to limit the scope of the temporary values before extracting the method.

With your code, I would change from

Parser parser = Parser.createParser(comment.getText(), "UTF-8");
NodeList htmlAnchorNodes = null;
try {
    htmlAnchorNodes = parser
            .extractAllNodesThatMatch(new TagNameFilter("a"));
} catch (ParserException e) {
    e.printStackTrace();
}

int size = htmlAnchorNodes.size();

to

int size;

{
    Parser parser = Parser.createParser(comment.getText(), "UTF-8");
    NodeList htmlAnchorNodes = null;
    try {
        htmlAnchorNodes = parser
                .extractAllNodesThatMatch(new TagNameFilter("a"));
    } catch (ParserException e) {
        e.printStackTrace();
    }
    size = htmlAnchorNodes.size();
}

The only assignment which has an effect outside of the scope of the braces is the change to size, which should resolve the ambiguity for the refactoring tool.

like image 78
GargantuChet Avatar answered Oct 10 '22 01:10

GargantuChet