【问题标题】:Code duplication in methods when a value needs to be different but not the method当值需要不同但方法不需要时,方法中的代码重复
【发布时间】:2017-03-14 16:59:23
【问题描述】:

我有一个处理属性文件的类(最终用户将在其中将 OAuth2 消费者密钥和消费者秘密值)。

在这个类中,我有一个这样的方法:

// Get the consumer key or secret value
public String getConsumerKeyOrSecret(String keyOrSecret)
{
    String value = properties.getProperty(keyOrSecret);
    if ( value == null || value.isEmpty())
    {
        value = null;
    }
    return value;
}

这是实现此功能的最佳方式吗?在我看来,在另一个类中获取这些值的更方便的方法是为您需要的键调用两个单独的方法,这些方法的实现方式如下:

public String getConsumerKey()
{
    String consumerKey = properties.getProperty("consumer_key");
    if ( consumerKey == null || consumerKey.isEmpty())
    {
        consumerKey = null;
    }
    return consumerKey;     
}

public String getConsumerSecret()
{
    String consumerSecret = properties.getProperty("consumer_secret");
    if ( consumerSecret == null || consumerSecret.isEmpty())
    {
        consumerSecret = null;
    }
    return consumerSecret;      
}

但这不会被视为代码重复吗?解决这个问题的最佳方法是什么?

【问题讨论】:

  • 创建一个私有方法,您可以在其中执行此类检查(即== null 等),然后在继续之前从需要完成此检查的所有其他地方调用私有方法

标签: java methods code-duplication


【解决方案1】:

通过引入一个通用的私有方法,您可以使用第二种解决方案而无需重复。

public String getKey(){
    return getPropertyValueOrNull("key");
}

public String getSecret(){
    return getPropertyValueOrNull("secret");
}

private String getPropertyValueOrNull(String property){
    String value = properties.getProperty(property);
    if (value == null || value.isEmpty()){
        return null;
    }
    return value;  
}

【讨论】:

    【解决方案2】:

    您为用户提供了这两种零参数的方法。

    您将第一个方法保留为私有方法,用于实现一次查找。

    换句话说:避免代码重复,同时也为您的代码用户提供最易于使用的界面。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-02
      • 1970-01-01
      • 2012-10-25
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      相关资源
      最近更新 更多