Refactoring method parameters

Imagine following code:

     public void method(String currentText) {           Matcher matcher = getMatcher(currentText);           while (matcher.find()) {                doSomething(currentText, matcher.start(), matcher.end());           }      }      private void doSomething(String currentText, int start, int end) {           System.out.println(currentText.substring(start, end));      }      private Matcher getMatcher(String currentText) {           return null;      }



I would like to refactor it so that the "matcher" will be passed as parameter into #doSomething

But how to do it easily?

When I try to use ctrl+alt+n, it makes this abomination:

     public void method(String currentText) {           Matcher matcher = getMatcher(currentText);           while (matcher.find()) {                doSomething(currentText);           }      }      private void doSomething(String currentText) {           int end = getMatcher(currentText).end();           int start = getMatcher(currentText).start();           System.out.println(currentText.substring(start, end));      }      private Matcher getMatcher(String currentText) {           return null;      }



What I want is this:

     public void method(String currentText) {           Matcher matcher = getMatcher(currentText);           while (matcher.find()) {                doSomething(currentText, matcher);           }      }      private void doSomething(String currentText, final Matcher matcher) {           int end = matcher.end();           int start = matcher.start();           System.out.println(currentText.substring(start, end));      }      private Matcher getMatcher(String currentText) {           return null;      }

2 comments

You may extract method from doSomething(currentText, matcher.start(), matcher.end()); name it doSomething and then inline the old method inside this on. Then you'll get
{code}

   public void method(String currentText) {
        Matcher matcher = getMatcher(currentText);
        while (matcher.find()) {
            doSomething(currentText, matcher);
        }
    }

    private void doSomething(String currentText, Matcher matcher) {
        System.out.println(currentText.substring(matcher.start(), matcher.end()));
    }

    private Matcher getMatcher(String currentText) {
        return null;
    }


{code}
0

Please sign in to leave a comment.