Reputation: 361
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?
Upvotes: 2
Views: 80
Reputation: 131326
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;
}
Upvotes: 1
Reputation: 140407
You give your users those two methods that go with zero arguments.
You keep your first method as private one around, to be used to implement that lookup once.
In other words: avoid the code duplication, but also give the most easy to use interface to users of your code.
Upvotes: 1