【问题标题】:<SomeThirdPartyClass>Util == God object?<SomeThirdPartyClass>Util == 上帝对象?
【发布时间】:2015-11-07 04:12:34
【问题描述】:

我使用Selenium Webdriver a lot,并且我编写了很多“实用”方法以使其更易于使用。我将这些类放在WebDriverUtil 类中,现在该文件的长度超过了 1,200 行。 WebDriverUtil 中的每个方法都试图将我与使用 WebDriver 分开,因为这是我经常使用的东西,而不是 DRY 继续写作。

例如,这是我将在WebDriverUtil 中输入的方法。

public void waitUntilVisible(final WebElement webElement) {
    new WebDriverWait(webDriver, 10).until(new Predicate<WebDriver>() {
        @Override
        public boolean apply(WebDriver webDriver) {
            return webElement.isDisplayed();
        }
    });
}

如果我有 1,200 行代码中充满了这样的方法,我有 God object 吗?如果是这样,我该如何解决?

我应该像这样将我的行为分成装饰器类吗?

public class WebElementDecorator implements WebElement {
    private WebElement webElement;
    private final WebDriver webDriver;

    public WebElementDecorator(WebElement webElement, WebDriver webDriver) {
        this.webElement = webElement;
        this.webDriver = webDriver;
    }

    public void waitUntilVisible() {
        new WebDriverWait(webDriver, 10).until(new Predicate<WebDriver>() {
            @Override
            public boolean apply(WebDriver webDriver) {
                return webElement.isDisplayed();
            }
        });
    }

    public void click() {
        webElement.click();
    }

    //... other WebElement methods
}

【问题讨论】:

  • 为什么不创建static的方法呢?它是否依赖于 Util 类中的任何状态?
  • @ElliottFrisch 在实用程序或装饰器中使其成为静态?

标签: java selenium design-patterns decorator god-object


【解决方案1】:

如果我有 1200 行这样的方法,我有上帝对象吗?

仅凭代码行数并不能充分表明一个类是否像上帝。由于糟糕的编码风格、过度工程、过度专业化方法的不同变体、冗长的语言、内联的 cmets 等,一个类可能会被代码臃肿。

一个神级是一个臃肿的责任。这里有两个试金石,可以确定你的 util 类是否已经进化成神类:

  1. 更改测试时对 util 类的影响。如果对测试子集的更改导致您经常更改和重新编译您的 util 类,那么这可能表明您的 util 类服务于太多的 master。理想的情况是,对测试子集的更改只会影响与测试直接相关的那些 util 方法(如有必要)。

  2. 更改 util 类时对测试类的影响。如果更改 util 类的一部分会导致许多不相关测试出现意外失败,那么您的 util 类可能已经将其触手遍及您的测试。

如果是这样,我该如何解决?我应该像这样将我的行为分成装饰器类吗?

最好以小的增量步骤开始重构。使用您的代码示例,我将首先将所有Wait..Until..Predicate 代码提取到一个名为WaitUntilEvent() 或其他名称的单独类中,使用isVisible()isEnabled()isSelected() 等方法。示例用法如下所示:

WaitUntilEvent waitUntil = new WaitUntilEvent(webElement, webDriver);
waitUntil.isVisible();
webElement.click();
// etc..

如果我需要围绕Wait..Until..Predicate 更改我的测试要求(例如超时间隔),我知道只有一个类需要编辑。然后可以将其进一步重构为until(PredicateIsTrue).then(PerformAction)until(FunctionIsTrue).then(PerformAction) 等。我更喜欢这种方法而不是包罗万象的神一样的class WebElementDecorator,它可能最终会使用许多装饰方法来捕获许多不同的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-07
    • 2013-01-24
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多