[英]I have been working on this code and I called my method replaceLessThan(x,e), and I can't properly write this method
[英]How to optimize my code using temple method or generic method or other method?Now I have to write the similar code three times
現在,我想將消息發送給可能是學生,老師或校長的人,他們所有人都有電話,姓名和availdSendMsgCount。在發送消息之前,這意味着將數據插入數據庫,我必須判斷他們是否可以無論是否發送,所以我寫這樣的代碼:
if(sendType=SendType.student){
List<Student> students=tStudentServiceImpl.queryByParam(conditionMap);
sendPhoneCout=students.size();
checkSendNumber(availdSendMsgCount,sendPhoneCout);
Log log=logMsgSend(content,sendPhoneCout,sendType);
for (Student vo : students)
sendMsgItem(content,vo.getPhone(),vo.getName(),vo.getId(),log.getId());
}
else if(sendType=SendType.teacher){
List<Teacher> teachers=tTeacherServiceImpl.queryByParam(conditionMap);
sendPhoneCout=teachers.size();
checkSendNumber(availdSendMsgCount,sendPhoneCout);
Log log=logMsgSend(content,sendPhoneCout,sendType);
for (Teacher vo : teachers)
sendMsgItem(content,vo.getPhone(),vo.getName(),vo.getId(),log.getId());
}
else{
List<Schoolmaster> schoolmasters=tSchoolmasterServiceImpl.queryByParam(conditionMap);
sendPhoneCout=schoolmasters.size();
checkSendNumber(availdSendMsgCount,sendPhoneCout);
Log log=logMsgSend(content,sendPhoneCout,sendType);
for (Schoolmaster vo : schoolmasters)
sendMsgItem(content,vo.getMasterPhone(),vo.getMasterName(),vo.getId(),log.getId());
}
我認為這段代碼不好,但是如何優化呢?
當校長,老師和學生實現相同的接口或超類時,則可以編寫一個使用List作為參數的方法,該方法可以完成所有工作,並且在三種情況下都將被調用。
另一方面,為什么會有三個不同的班級? 他們似乎有完全相同的方法。 一個類型參數決定它是哪種類型還不夠嗎?
我建議您創建一個接口並在您的dao類中實現它,這樣每個接口的行為都會有所不同。
public interface NameMe {
void sendMsgItem(content, Integer logId); // it's not clear the type of content
}
有方法
// replace T with type of 'conditionMap' object, it's not clear from your code
public static void getAndSendMessageItems(Function<T, List<NameMe>> serviceFunc,
T conditionMap, Integer availdSendMsgCount, SendType sendType) {
List<NameMe> values = serviceFunc.apply(conditionMap);
Integer sendPhoneCout = values.size();
checkSendNumber(availdSendMsgCount, sendPhoneCout);
Log log = logMsgSend(content, sendPhoneCout, sendType);
for (NameMe i : values) {
i.sendMsgItem(content, log.getId());
}
}
並在您的if / else中調用它
Function<T, List<NameMe>> serviceFunc = null;
if (SendType.student.equals(sendType)) {
serviceFunc = tStudentServiceImpl::queryByParam;
} else if (SendType.teacher.equals(sendType)) {
serviceFunc = tTeacherServiceImpl::queryByParam;
} else {
serviceFunc = tSchoolmasterServiceImpl::queryByParam;
}
getAndSendMessageItems(serviceFunc, conditionMap, availdSendMsgCount, sendType);
但是,如果您的服務實現相同的接口,則甚至不需要使用Function<T, List<NameMe>>
,您只需通過接口對象傳遞服務即可。
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.