使用 config mapping 避免程式碼中 if-else 語句過多
阿新 • • 發佈:2018-12-20
此方法轉自stackoverflow
當前程式碼為:
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(); }
可重構為:
Map<String,String> map = new HashMap<String,String>(); map.put("EditorialOffice",""); map.put("EditorialBoard",""); map.put("AdvisoryBoard",""); // could make constants for above Strings, or even an enum if(eventType == XmlPullParser.START_TAG) { soapResponse= xpp.getName().toString(); String current = map.get(soapResponse); if (current != null) { eventType = xpp.next(); if (xpp.getText()!=null){ map.put( soapResponse, current += xpp.getText()); } } eventType = xpp.next(); }