我有一个处理属性文件的类(最终用户将在其中使用 OAuth2 消费者 key 和消费者 secret 值)。
在这个类中我有一个像这样的方法:
// 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;
}
但这不会被认为是代码重复吗?解决这个问题的最佳方法是什么?
最佳答案
您可以通过引入通用的私有(private)方法来使用第二种解决方案,而无需重复。
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;
}
关于java - 当值需要不同但方法不需要不同时,方法中会出现代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42792114/