Home > Back-end >  How to refactor code and combine 4 methods in 1 in Java
How to refactor code and combine 4 methods in 1 in Java

Time:08-17

I have methods for Selenium test. Actions similar for each other. I need to combine this 4 methods in 1 for better code-style, but do not have a lot of experience for this implementation.

public List<String> ticketId() {
        List<WebElement> ticketId = driver.findElements(ticketsIdLocator);
        List<String> ticketsIdList = new ArrayList<>();
        for (int i = 0; i < ticketId.size(); i  ) {
            ticketsIdList.add(ticketId.get(i).getText());
        }
        return ticketsIdList;
    }

public List<String> ticketTitle() {
    List<WebElement> ticketTitle = driver.findElements(ticketsTitleLocator);
    List<String> ticketTitleList = new ArrayList<>();
    for (int i = 0; i < ticketTitle.size(); i  ) {
        ticketTitleList.add(ticketTitle.get(i).getText());
    }
    return ticketTitleList;
}

public List<String> ticketsAssignee() {
    List<WebElement> ticketsAssignee = driver.findElements(ticketsAssigneeLocator);
    List<String> ticketsAssigneeList = new ArrayList<>();
    for (int i = 0; i < ticketsAssignee.size(); i  ) {
        ticketsAssigneeList.add(ticketsAssignee.get(i).getText());
    }
    return ticketsAssigneeList;
}

public List<String> ticketsStage() {
    List<WebElement> ticketsStage = driver.findElements(ticketsStageLocator);
    List<String> ticketsStageList = new ArrayList<>();
    for (int i = 0; i < ticketsStage.size(); i  ) {
        ticketsStageList.add(ticketsStage.get(i).getText());
    }
    return ticketsStageList;
}

CodePudding user response:

some hints:

  • the only difference in the locator. So, just pass it as a method param. Something like findByLocator(ticketsStageLocator)
  • you can replace for (int i=0.. , i ) , with for (WebElement el: ticketsStage) or even with stream driver.findElements(ticketsStageLocator).stream().map(...).collect(Collectors.toList());

CodePudding user response:

I have rewrite code, but still do not have solution

public class TicketsPage {
    public TicketsPage ticketColumns() {
        List<WebElement> ticketId = driver.findElements(ticketsIdLocator);
        List<WebElement> ticketTitle = driver.findElements(ticketsTitleLocator);

        List<String> ticketIdList = this.ticketsBase(ticketId);
        List<String> ticketTitleList = this.ticketsBase(ticketTitle);
    }
    public List<String> ticketsBase(List<WebElement> ticketElements) {
        List<String> ticketListBase = new ArrayList<>();

        for (int i = 0; i < ticketElements.size(); i  ) {
            ticketListBase.add(ticketElements.get(i).getText());
        }
        return ticketListBase;
    }
}
  • Related