【发布时间】: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