Java 当值需要不同而不是方法时,方法中的代码重复

Java 当值需要不同而不是方法时,方法中的代码重复,java,methods,code-duplication,Java,Methods,Code Duplication,我有一个处理属性文件的类(最终用户将在其中处理OAuth2使用者密钥和使用者秘密值) 在这门课上,我有一个这样的方法: // Get the consumer key or secret value public String getConsumerKeyOrSecret(String keyOrSecret) { String value = properties.getProperty(keyOrSecret); if ( value == null || value.isE

我有一个处理属性文件的类(最终用户将在其中处理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;      
}
这是实现这一目标的最佳方式吗?在我看来,在另一个类中获取这些值的更方便的方法是为所需的键调用两个单独的方法,方法实现如下:

// 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;      
}

但这不被认为是代码重复吗?最好的方法是什么?

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

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


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

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

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;  
}

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