2017-03-14 6 views
2

최종 사용자가 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;  
} 

을하지만 이것은 코드 중복으로 간주되지 않을 것이다? 이것을 접근하는 가장 좋은 방법은 무엇입니까?

+0

이 유형의 검사 (예 :'== null '등)를 수행하는 개인 메소드를 작성한 후 진행하기 전에이 검사가 필요한 다른 모든 장소에서 개인 메소드를 호출하십시오. – ochi

답변

1

일반적인 개인 메서드를 도입하여 중복없이 두 번째 솔루션을 사용할 수 있습니다.

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

사용자에게 0 인수가있는 두 가지 방법을 제공합니다.

당신은 첫 번째 방법을 개인적인 것으로 주변에두고, 해당 룩업을 한 번 구현하는 데 사용합니다.

다른 말로하면 : 코드 중복을 피하면서도 코드 사용자에게 가장 사용하기 쉬운 인터페이스를 제공하십시오.