How to implement the best OOP

I am developing a WebDriver [Java] selenium structure in which there is a base class, and every other class extends from this class. In addition, I follow the Page Object Model, where each page corresponds to a class and the method in which it moves to the next page returns a new instance of the next page / class. In short, each page of the user interface corresponds to a class

Now every page has some common functions, so instead of putting them in every class and avoiding DRY, I put this in the base page class

for ex goBack, the method is on every page, which basically moves to the previous page.

My concern is that I want to keep track of the chain between pages / classes and, therefore, I'm not sure what the return type of common ex goBack methods should be.

Remember that any method that goes to the next page should return a new instance of this page.

One solution I thought was introducing Generics, but still struggling. Can someone help me on how I can achieve this.

public class BasePage { public WebDriver driver; public BasePage(WebDriver driver) { this.driver=driver; } public BasePage clickGoBack() throws Exception{ driver.click(goBackButton); return this; } } 
+5
source share
1 answer

BasePage must know the type of implementation for the chain:

 /** * @param <T> The implementing type. */ public abstract class BasePage<T extends BasePage<T>> {} 

Then you can use:

 public T clickGoBack() { return (T) this; } 

The problem here is that this not necessarily an instance of T , so casting is not safe, for example with the following class:

 public class Page1 extends BasePage<Page2> {} 

The solution is to ask subclasses of their this :

 public abstract class BasePage<T extends BasePage<T>> { protected final WebDriver driver; public BasePage(WebDriver driver) { this.driver = driver; } public T clickGoBack() throws Exception{ driver.click(goBackButton); return getThis(); } protected abstract T getThis(); } public class HomePage extends BasePage<HomePage> { public HomePage(WebDriver driver) { super(driver); } @Override protected HomePage getThis() { return this; } } 
+7
source

All Articles