Search code examples
javamethodscode-duplication

Code duplication in methods when a value needs to be different but not the method


I have a class that handles a properties file (in which the end user will OAuth2 consumer key and consumer secret values).

In this class I've got a method like this:

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

Is this the best way to implement this? In my opinion the more convenient way to get these values in another class would be to call two separate methods for the key you need, and the methods implemented like this:

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

But would not this be considered code duplication? What is the best way to approach this?


Solution

  • You can use the second solution without duplication by introducing a common private method.

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