我已經閱讀了很多關於代碼重構和避免if else語句的主題。 其實,我有一個課,我使用了很多if - else條件。如何避免很多其他條件
更多細節:我使用的是拉解析器和我SOAP響應的每一行,我會檢查是否有標籤我感興趣的,如果沒有,檢查另一個標記等:
if(eventType == XmlPullParser.START_TAG) {
soapResponse= xpp.getName().toString();
if (soapResponse.equals("EditorialOffice")){
eventType = xpp.next();
if (xpp.getText()!=null){
editorialOffice += xpp.getText();
}
}
else if (soapResponse.equals("EditorialBoard")){
eventType = xpp.next();
if (xpp.getText()!=null){
editorialBoard += xpp.getText();
}
}
else if (soapResponse.equals("AdvisoryBoard")){
eventType = xpp.next();
if (xpp.getText()!=null){
advisoryBoard += xpp.getText();
}
}
}
eventType = xpp.next();
}
現在,我想用其他的,而不是那些如果其他條件,但我不知道是什麼。
你可以給我一個例子或一個很好的教程頁嗎?
謝謝。
你可以維護字符串到程序中其他地方的枚舉映射,從映射中抽出與返回字符串關聯的枚舉(如果字符串不在映射中,則使用默認的'NO_MATCH')並寫入在枚舉上切換語句。它可能會使代碼更清晰,但會增加額外的間接層。你必須判斷這是否值得。 – 2012-04-16 14:24:42
檢查: http://stackoverflow.com/questions/519422/what-is-the-best-way-to-replace-or-substitute-if-else-if-else-trees-在程序中 希望對您有所幫助 – 2012-04-16 14:27:54
請注意,出於性能方面的原因,您應該使用StringBuilder而不是+ =來連接字符串。 – 2012-04-19 14:40:19