2011-10-21 31 views
1
categoryCheck: { 
     for (String allowedCategory : allowedCategories) { 
      if (evt.getLoggerName().startsWith(allowedCategory)) { 
       break categoryCheck; 
      } 
     } 
     return false; 
    } 

是否有任何想法如何重寫這段代碼,而不使用標籤,沒有顯着增加它?如何在不使用標籤的情況下重寫java代碼?

+1

簡單的休息就足夠了,因爲沒有嵌套循環 – Hachi

+1

這將導致它返回false; –

回答

6

我可能會把它變成自己的方法:

// I've guessed at the types... 
public boolean isCategoryAllowed(Event evt, Iterable<String> allowedCategories) { 
    for (String allowedCategory : allowedCategories) { 
     if (evt.getLoggerName().startsWith(allowedCategory)) { 
      return true; 
     } 
    } 
    return false; 
} 

然後改變調用代碼,只需調用方法:

if (!isCategoryAllowed(evt, allowedCategories)) { 
    return false; 
} 
1

下面是一個使用布爾標誌的直接等價的:

boolean found = false; 
    for (String allowedCategory : allowedCategories) { 
     if (evt.getLoggerName().startsWith(allowedCategory)) { 
      found = true; 
      break; 
     } 
    } 
    if (!found) { 
     return false; 
    } 
    // ...the rest of the method's code... 
1
boolean matched = false; 

for (String allowedCategory : allowedCategories) { 
    if (evt.getLoggerName().startsWith(allowedCategory)) { 
     matched = true; 
     break; 
    } 
} 

if (!matched) 
    return false; 

// else continue with the rest of the code 
1

你可以使用一個標誌。

boolean found = false; 
for (String allowedCategory : allowedCategories) { 
    if (evt.getLoggerName().startsWith(allowedCategory)) { 
     found = true; 
     break; 
    } 
} 
if(!found) 
    return false; 
相關問題