开发者

What's the point of a copied / duplicate reference variable?

I just saw the following code:

public static void initElements(WebDriver driver, Object page) {
    final WebDriver driverRef = driver;
    initElements(new DefaultElementLocatorFactory(driverRef), page);
}

Can somebody tell me, what's the advantage of writing this instead of:

public static void initElements(WebDriver driver, Object page) {
    initElements(new DefaultElementLocatorFactory(driver), page);
}

I hope my first question here isn't too pointless and/or stupid and youi have fun answering it!

(Code quote f开发者_Go百科rom org.openqa.selenium.support.PageFactory; Copyright 2007-2009 WebDriver committers; Copyright 2007-2009 Google Inc.)


There's no difference in application behavior. However such pattern might be used when:

  • wanting to provide a local name of the value which is better suited in this context. Here it's driverRef vs driver, which doesn't bring any value, but in other cases it might
  • wanting to make the variable accessible as a local variable for debugger. Debuggers may treat local variables and class fields differently (e.g. when presenting their values), but it's hard to justify such a change to be made permamently
  • caring of readability. Here the replaced expression is simple - just driver, but sometimes you have a more complicated expression which would make the line too long if inlined.


In this case I don't see any point. But I can see a point to declare variable as final. So this is going to be sufficient:

public static void initElements(final WebDriver driver, Object page) {
    initElements(new DefaultElementLocatorFactory(driver), page);
}


I think the 'final' keyword is the answer to your question.

final means the reference cannot be reassigned.


As already said, in the code you posted there's really no point.

One reason for making a variable final is when you want to use it in an anonymous inner class inside the method. A variable must be final to be able to be accessed inside the anonymous inner class. A somewhat silly example, just to illustrate the point:

public static void initElements(final WebDriver driver, final Object page) {
    // Anonymous inner class
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // The variables must be final, otherwise you can't access them here
            initElements(new DefaultElementLocatorFactory(driver), page);
        }
    };

    runnable.run();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜