【发布时间】:2020-02-01 06:58:09
【问题描述】:
我有一个很长的 switch 语句代码(大约 8 个案例),它决定使用什么搜索来在浏览器中查找元素。 有什么建议如何重构这段代码?
WebElement CurrentObject = null; 开关(搜索){ 案例“类名”: 尝试 { CurrentObject = new WebDriverWait(驱动程序,ConstantValues.LONGWAIT) .until(ExpectedConditions.presenceOfElementLocated(By.className(SearchPar))); } 捕捉(异常 e){ System.out.println("未找到元素:" + e); } 打破;
case "cssSelector":
try {
CurrentObject = new WebDriverWait(driver, ConstantValues.LONGWAIT)
.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(SearchPar)));
} catch (Exception e) {
System.out.println("Element not found: " + e);
}
break;
case "id":
try {
CurrentObject = new WebDriverWait(driver, ConstantValues.LONGWAIT)
.until(ExpectedConditions.presenceOfElementLocated(By.id(SearchPar)));
} catch (Exception e) {
System.out.println("Element not found: " + e);
}
break;
case "linkText":
try {
CurrentObject = new WebDriverWait(driver, ConstantValues.LONGWAIT)
.until(ExpectedConditions.presenceOfElementLocated(By.linkText(SearchPar)));
} catch (Exception e) {
System.out.println("Element not found: " + e);
}
break;
case "name":
try {
CurrentObject = new WebDriverWait(driver, ConstantValues.LONGWAIT)
.until(ExpectedConditions.presenceOfElementLocated(By.name(SearchPar)));
} catch (Exception e) {
System.out.println("Element not found: " + e);
}
break;
default:
System.out.println(">>> SEARCH BY KEYWORD IS NOT VALID! <<<");
}
【问题讨论】:
-
重构问题可能更适合codereview.stackexchange.com/tour
-
你试过什么?你被困在哪里了?提示:查看重复的代码并尝试将其移出 switch 语句。
-
@ErwinBolwidt 此代码正在运行,发现我只需要建议以使其更好。我已经在考虑删除重复代码并创建一个函数然后调用它的想法