關於代碼重構:問題如下
各個科目都對應一個“考試”的實體bean,各個對象裡部分屬性是一致的,也存在不同的屬性。經常遇到的情況是要寫好幾套代碼。
如下面的代碼片段
if ("1".equals(subjectCode)) {
LogUtil.info("獲取數學");
TestM testM = new TestM();
testM.setTeachingCode(teachingVersionCode);
testM.setGradeCode(gradeCode);
testM.setTermCode(Integer.valueOf(termCode));
testM.setQuesTestTypeCode(Integer.valueOf(testTypeCode));
List<TestM> resultList = testService.getTestMList(testM,pageNo);
int pageCount = testService.getPaperMCount(testM);
}
if ("2".equals(subjectCode)) {
LogUtil.info("獲取英語");
TestE testE = new TestE();
testE.setTeachingCode(teachingVersionCode);
testE.setGradeCode(gradeCode);
testE.setTerECode(Integer.valueOf(terECode));
testE.setQuesTestTypeCode(Integer.valueOf(testTypeCode));
List<TestE> resultList = testService.getTestEList(testE,pageNo);
int pageCount = testService.getPaperECount(testE);
}
if ("3".equals(subjectCode)) {
LogUtil.info("獲取語文");
TestC testC = new TestC();
testC.setTeachingCode(teachingVersionCode);
testC.setGradeCode(gradeCode);
testC.setTerCCode(Integer.valueOf(terCCode));
testC.setQuesTestTypeCode(Integer.valueOf(testTypeCode));
List<TestC> resultList = testService.getTestCList(testC,pageNo);
int pageCount = testService.getPaperCCount(testC);
}
請教如何進行優化會比較好一點?
1、看著你這裡是set值後去獲取信息了,這裡的優化是:可以弄個構造方法,這樣就不用總set了;
2、關於獲取後賦值的,你可以這麼做:JSONObject testm_obj = JSONObject.fromObject(test_str);
TestM TestM_vo = (TestM )JSONObject.toBean(testm_obj, TestM .class);
3、創建bean類時,可以把相同的屬性寫成父類