I have seen examples put all the By locator fields at the top as instance variables, but if they are only used once within a method surely they should be local? Which is cleaner and easier to read?
-
java doesn't support global variables. What do you mean, instance or static variables? – Stultuske Oct 20 '22 at 11:40
-
sorry yeah i think ive mixed up the definitions, im new to java – teaaa Oct 20 '22 at 12:02
1 Answers
Even if they are used only once, its good practice to declare all the page elements at the class level. You may also mention it as static variable. A simple example for your perusal. Even though we use Hamburger icon only once, we still declare them at the top level. Since static variable, we are going to have only one object created for this at any point of time.
public class HomePage {
private static By byHamburgerIcon = By.xpath("//div[contains(@class,'icon-hamburger')]");
private static By byHeaderName = By.cssSelector("div[name='username']");
public void clickHamburgerIcon() {
PageActionHelper.click(byHamburgerIcon,"Clicked Hamburger icon");
}
}
This way it would be easier to refactor if any changes happened in future.
Also, there is high chance that we would use the locator in multiple places of the class. At those times, if we mention locator directly inside method, we would need to duplicate them. Changes on those locator need to be made everywhere. These are error prone. Hence having a single locator declared at the class level would be a better way.

- 512
- 1
- 5
- 18