如何写好的代码.ppt

上传人:本田雅阁 文档编号:2599159 上传时间:2019-04-15 格式:PPT 页数:70 大小:962.51KB
返回 下载 相关 举报
如何写好的代码.ppt_第1页
第1页 / 共70页
如何写好的代码.ppt_第2页
第2页 / 共70页
如何写好的代码.ppt_第3页
第3页 / 共70页
如何写好的代码.ppt_第4页
第4页 / 共70页
如何写好的代码.ppt_第5页
第5页 / 共70页
点击查看更多>>
资源描述

《如何写好的代码.ppt》由会员分享,可在线阅读,更多相关《如何写好的代码.ppt(70页珍藏版)》请在三一文库上搜索。

1、如何写好的代码,数融信息技术有限公司 冯国平,什么是好的代码,问题: 什么是好的代码? 什么是坏的代码?,什么是好的代码,代码要人能够读懂-Martin Fowler 任何一个傻瓜都能写出机器能懂的代码,好的程序员应该写出人能读懂的代码。 -Martin Flowler 重构,什么是好的代码,代码是给人看的-Harold Abelson 程序必须是写给人看的,仅仅偶尔才在机器上执行。 -Harold Abelson等人,什么是好的代码,程序是人-Steve McConnell 编写程序首先为人,其次为计算机。 -Steve McConnell,什么是好的代码,写烂代码是危险的-Martin G

2、olding 编程的时候,总是想着那个维护你代码的人是一个只读你住在什么地方的、有着暴力倾向的精神病患者。 -Martin Golding,什么是好的代码,结论 好的代码有很多评价标准,但最重要的标准是 “易于理解,人能读懂!”,代码的坏味道,什么是代码的坏味道 是一个形象的比喻,由Martin Flower提出。 代码坏味道:是指在代码之中潜在问题的警示信号。 并非所有的坏味道所指示的确实是问题,但是对于绝大多数坏味道,均很有必要加以查看,并作出相应的修改。,代码的坏味道,hard code 1.读不懂 qps.add(qpbInvalid); getMulQueryParaBeans(“s

3、tatus”, “1,3”, qps, false); List organizations = orgDataService.getOrgAll(); List employees = orgDataService .getEmployeePositionAll(“000001“);/temp 2.引入bug隐患 commonService.update(user); MailAccount mailAccount = mailAccountService.getMailAccount(userId); if (mailAccount != null) user.setMailAccount

4、(mailAccount); mailManageService.connectReceive(mailAccount); setUser(user); setCurLanguage(“zh_CN“);,代码的坏味道,hard code String replayInfo =“-,代码的坏味道,hard code 3.难以扩展 if (!filepath.endsWith(“.jpg“) ,代码的坏味道,hard code 4.解决之道 .引入常量 List employees = orgDataService.getEmployeePositionAll(“000001“);/temp pr

5、ivate static final String BOSS_EMPLOYEE_CODE = “000001“; List employees = orgDataService.getEmployeePositionAll(BOSS_EMPLOYEE_CODE);/temp,代码的坏味道,hard code .引入国际化处理 String replayInfo =“-,代码的坏味道,hard code .读配置 if (!filepath.endsWith(“.jpg“) ,代码的坏味道,魔法数字 1.读不懂 for (int i = 0; i 200 | height 200) errorS

6、tr = “图片宽高不能超过200像素“; ftpUtil.deleteFile(filePath); ,代码的坏味道,魔法数字 job.setStatus(0); / 默认未发布 job.setInvalid(0); / 默认未删除 3.类型 if(linkman=1) return companyContactDao.setLinkman(companyId,id,linkman); else if(linkman=0) return companyContactDao.removeLinkman(companyId,id,linkman); if(jobDeliver.getRecomm

7、endOrDeliver().equals(1) fromTo = 1; else fromTo = 2; resumeJob.setInvite(1); resumeJob.setFromTo(2); resumeJob.setReading(0); resumeJob.setInvalid(0); resumeJob.setIsReply(0L);,代码的坏味道,魔法数字 if(checkcode = null | !code.equals(checkcode) return 0; User user = this.us.findUnique(“from User as u where u

8、.userName = ?“, username); if(user = null) return 1; /待删除 this.userId = user.getId(); if(!password.equals(user.getPassword() return 2; 4.可以允许的数字 for (int i = 0; i 0 ,代码的坏味道,魔法数字 5.解决之道 引入常量 if (width 200 | height 200) errorStr = “图片宽高不能超过200像素“; ftpUtil.deleteFile(filePath); private static final int

9、 DEFULT_IMG_SIZE = 200; if (width DEFULT_IMG_SIZE | height DEFULT_IMG_SIZE) errorStr = “图片宽高不能超过”+ DEFULT_IMG_SIZE +”像素“; ftpUtil.deleteFile(filePath); ,代码的坏味道,魔法数字 5.解决之道 使用枚举类型 if(linkman=1) return companyContactDao.setLinkman(companyId,id,linkman); else if(linkman=0) return companyContactDao.remo

10、veLinkman(companyId,id,linkman); enum OperationType modify,delete; if(linkman= OperationType.modify) return companyContactDao.setLinkman(companyId,id,linkman); else if(linkman= OperationType.delete) return companyContactDao.removeLinkman(companyId,id,linkman);,代码的坏味道,重复代码 1.完全重复 if (companyId = null

11、) Company c = new Company(); c.setUserId(userId); companyService.save(c); companyId = c.getId(); String corpIdx = companyId.toString(); int companyIdStrLength = corpIdx.length(); for (int i = 0; i 6 - companyIdStrLength; i+) corpIdx = “0“ + corpIdx; c.setCorpIdx(corpIdx); companyService.saveOrUpdate

12、(c); else Company company = companyService.get(companyId); if (company.getCorpIdx() = null) String corpIdx = companyId.toString(); int companyIdStrLength = corpIdx.length(); for (int i = 0; i 6 - companyIdStrLength; i+) corpIdx = “0“ + corpIdx; company.setCorpIdx(corpIdx); companyService.saveOrUpdat

13、e(company);,代码的坏味道,重复代码 public ModelAndView open(Long id,HttpServletRequest request, HttpServletResponse response) throws TException Resume resume = resumeService.get(id); model.addObject(“resume“, resumeService.get(id); model.addObject(“personal“, resumeService.getPersonal(id); model.addObject(“job

14、Target“,jobTargetMap); model.addObject(“languages“, resumeService.getLanguages(id); model.addObject(“languageAchieve“, resumeService.getLanguageAchieve(id); model.addObject(“additional“, resumeService.getAdditionalInfo(id); model.addObject(“selfRecommends“, resumeService.getSelfRecommends(id); model

15、.addObject(“educationExperinces“, educationService.findbyResumeId(id); model.addObject(“jobExperiences“, jobExperiencesList); model.addObject(“projectExperiences“, projectService.findbyResumeId(id); model.addObject(“skills“, resumeService.getSkills(id); model.addObject(“trainningExperiences“, trainn

16、ingService.findbyResumeId(id); model.addObject(“certificates“, resumeService.getCertificates(id); model.addObject(“others“, resumeService.getOthers(id); model.addObject(“attachments“, resumeService.getAttachments(id); model.addObject(“privateSpace“, resumeService.getPrivateSpace(id); model.addObject

17、(“privateAttachments“, resumeService.getPrivateAttachments(id);,代码的坏味道,重复代码 model.addObject(“printColumns“, resumeService.getPrintColumns(id); model.addObject(“basicData“, basicDataService.getStaticDataByCodeTypeAndLanguage(resumeService.get(id).getLanguage(), RESUME_BASICDATA_CODE); model.addObject

18、(“curLanguage“,resumeService.get(id).getLanguage(); return model; public ModelAndView inResumeGraduate(Long id) ModelAndView model = new ModelAndView(“/resume/resumeGraduate“); model.addObject(“resume“, resumeService.get(id); model.addObject(“personal“, resumeService.getPersonal(id); model.addObject

19、(“jobTarget“, jobTargetMap); model.addObject(“languages“, resumeService.getLanguages(id); model.addObject(“languageAchieve“, resumeService.getLanguageAchieve(id); model.addObject(“selfRecommends“, resumeService.getSelfRecommends(id); model.addObject(“educationExperinces“, educationService.findbyResu

20、meId(id); model.addObject(“skills“, resumeService.getSkills(id); model.addObject(“trainningExperiences“, trainningService.findbyResumeId(id); model.addObject(“certificates“, resumeService.getCertificates(id); model.addObject(“others“, resumeService.getOthers(id); model.addObject(“attachments“, resum

21、eService.getAttachments(id); model.addObject(“privateSpace“, resumeService.getPrivateSpace(id); model.addObject(“privateAttachments“, resumeService.getPrivateAttachments(id); model.addObject(“printColumns“, resumeService.getPrintColumns(id); model.addObject(“rewards“,resumeService.getRewards(id); mo

22、del.addObject(“dutys“,resumeService.getDutys(id);,代码的坏味道,重复代码 model.addObject(“practices“,resumeService.getPractices(id); model.addObject(“basicData“, basicDataService.getStaticDataByCodeTypeAndLanguage(resumeService.get(id).getLanguage(), RESUME_BASICDATA_CODE); model.addObject(“curLanguage“,resume

23、Service.get(id).getLanguage(); return model; 2.功能重复 JobCommentController.java /* * 上传简历评论附件 * param request * return */ RequestMapping(value = “/uploadJobComment“, method = RequestMethod.POST ) public void uploadComment(RequestParam(“file“) CommonsMultipartFile file, HttpServletResponse response) if

24、 (file != null) FTPUtil ftpUtil = new FTPUtil(); try ftpUtil.connectServer(); String fileName = file.getFileItem().getName(); String filePath = FTP_JOB_COMMENT_DIR + UUID.randomUUID().toString() + “.“ + FilenameUtils.getExtension(fileName); Long fileSize= file.getFileItem().getSize(); ftpUtil.upload

25、(file.getInputStream(), filePath); response.setContentType(“text/html;charset=UTF-8“);PrintWriter writer = response.getWriter();,代码的坏味道,重复代码 writer.print(“ fileName: “ + fileName + “, filePath: “ + filePath + “, fileSize: “ + fileSize + “); writer.close(); catch (IllegalStateException e) logger.erro

26、r(e.getMessage(), e); catch (IOException e) logger.error(e.getMessage(), e); finally ftpUtil.closeServer(); ResumeCommentController.java /* * 下载简历评论附件 * param request * return */ RequestMapping(value = “/downloadResumeComment“, method = RequestMethod.GET) public ModelAndView downloadAttach(String fi

27、leName, String filePath, Long fileSize, HttpServletResponse response) HttpServletRequest request = getRequest(); BufferedInputStream bis = null; BufferedOutputStream bos = null; FTPUtil ftpUtil = new FTPUtil(); try ,代码的坏味道,重复代码 request.setCharacterEncoding(“UTF-8“); response.setContentType(“text/htm

28、l;charset=utf-8“); response.setContentType(“application/x-msdownload;“); response.setHeader(“Content-disposition“, “resumecomment; filename=“ + new String(fileName.getBytes(“utf-8“), “ISO-8859-1“); response.setHeader(“Content-Length“, String.valueOf(fileSize); ftpUtil.connectServer(); InputStream in

29、put = ftpUtil.downFile(filePath); bis = new BufferedInputStream(input); bos = new BufferedOutputStream(response.getOutputStream(); byte buff = new byte2048; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length) bos.write(buff, 0, bytesRead); catch (Exception e) e.printStackTrace();

30、 finally try if (bis != null) bis.close(); if (bos != null) bos.close(); ftpUtil.closeServer(); catch (IOException e) ,代码的坏味道,重复代码 e.printStackTrace(); return null; 3.抽象功能重复 model.addObject(“officeRequire“, officeRequirList.size() 0 ? officeRequirList.get(0) : null); model.addObject(“remuneration“,

31、remunerationList.size() 0 ? remunerationList.get(0) : null); model.addObject(“jobSetting“, jobSettingList.size() 0 ? jobSettingList.get(0) : null); if (pJobSearch.getEducationalBackground() != null ,代码的坏味道,重复代码 if (pJobSearch.getPosition() != null ,代码的坏味道,重复代码 4.数据交换 if (companys = null | companys.s

32、ize() = 0) Company company = companyService.findCompanyByUId(userId); Map companyInfo = new HashMap(); companyInfo.put(“companyId“, company.getId(); companyInfo.put(“companyName“, company.getCompanyName(); companyInfo.put(“logoPath“, company.getLogoPath(); companys.add(companyInfo); ,代码的坏味道,重复代码 5.解

33、决之道 提取方法 if (companyId = null) Company c = new Company(); c.setUserId(userId); companyService.save(c); companyId = c.getId(); String corpIdx = companyId.toString(); int companyIdStrLength = corpIdx.length(); for (int i = 0; i 6 - companyIdStrLength; i+) corpIdx = “0“ + corpIdx; c.setCorpIdx(corpIdx)

34、; companyService.saveOrUpdate(c); else Company company = companyService.get(companyId); if (company.getCorpIdx() = null) String corpIdx = companyId.toString(); int companyIdStrLength = corpIdx.length(); for (int i = 0; i 6 - companyIdStrLength; i+) corpIdx = “0“ + corpIdx; company.setCorpIdx(corpIdx

35、); companyService.saveOrUpdate(company);,代码的坏味道,重复代码 private String getCompIdx(Object companyId) String corpIdx = companyId.toString(); int companyIdStrLength = corpIdx.length(); for (int i = 0; i 6 - companyIdStrLength; i+) corpIdx = “0“ + corpIdx; return comIdx; if (companyId = null) Company c = n

36、ew Company(); c.setUserId(userId); companyService.save(c); companyId = c.getId(); c.setCorpIdx(getCompIdx(companyId); companyService.saveOrUpdate(c); else Company company = companyService.get(companyId); if (company.getCorpIdx() = null) company.setCorpIdx(getCompIdx(companyId); companyService.saveOr

37、Update(company);,代码的坏味道,重复代码 model.addObject(“officeRequire“,officeRequirList.size() 0 ? officeRequirList.get(0) : null); model.addObject(“remuneration“,remunerationList.size() 0 ? remunerationList.get(0) : null); model.addObject(“jobSetting“,jobSettingList.size() 0 ? jobSettingList.get(0) : null);

38、private Object getFirstMember(List list) return list.size()0?list.get(0):null; model.addObject(“officeRequire“,getFirstMember(officeRequirList); model.addObject(“remuneration“, getFirstMember(remunerationList); model.addObject(“jobSetting“, getFirstMember(jobSettingList);,代码的坏味道,重复代码 if (pJobSearch.

39、getPosition() != null ,代码的坏味道,重复代码 private boolean isPositive(Integer number) return number!=null,代码的坏味道,重复代码 if (companys = null | companys.size() = 0) Company company = companyService.findCompanyByUId(userId); Map companyInfo = new HashMap(); companyInfo.put(“companyId“, company.getId(); companyIn

40、fo.put(“companyName“, company.getCompanyName(); companyInfo.put(“logoPath“, company.getLogoPath(); companys.add(companyInfo); ,代码的坏味道,重复代码 Jodd API public void bean2Map(Object bean,String properties) Map companyInfo = new HashMap(); for(String property:properties) companyInfo.put(property,BeanUtil.g

41、etProperty(bean,property); return companyInfo; if (companys = null | companys.size() = 0) Company company = companyService.findCompanyByUId(userId); companys.add(bean2Map(company,new String“companyId”,” companyName”,” logoPath”); ,代码的坏味道,过长方法 public ResponseBody int login(String username, String pas

42、sword, String checkcode, HttpSession session, HttpServletRequest request) String code = (String)session.getAttribute(“validateCode“); if(checkcode = null | !code.equals(checkcode) return 0; User user = this.us.findUnique(“from User as u where u.userName = ?“, username); if(user = null) return 1; /待删

43、除 this.userId = user.getId(); if(!password.equals(user.getPassword() return 2; /保存登录信息 user.setBeforeOperateTime(user.getOperateTime(); user.setBeforeOperateHost(user.getOperateHost(); user.setOperateTime(new Date();,代码的坏味道,过长方法 user.setOperateHost(getRequest().getRemoteAddr(); if (user.getBeforeOpe

44、rateTime() = null) user.setBeforeOperateTime(user.getOperateTime(); if (user.getBeforeOperateHost() = null) user.setBeforeOperateHost(user.getOperateHost(); commonService.update(user); MailAccount mailAccount = mailAccountService.getMailAccount(user.getId(); if (mailAccount != null) user.setMailAcco

45、unt(mailAccount); mailManageService.connectReceive(mailAccount); setUser(user); return 3; ,代码的坏味道,过长方法 解决之道 提取方法 private boolean checkCode(HttpSession session) String code = (String)session.getAttribute(“validateCode“); return checkcode != null ,代码的坏味道,过长方法 解决之道 提取方法 user.setOperateTime(new Date();

46、user.setOperateHost(getRequest().getRemoteAddr(); if (user.getBeforeOperateTime() = null) user.setBeforeOperateTime(user.getOperateTime(); if (user.getBeforeOperateHost() = null) user.setBeforeOperateHost(user.getOperateHost(); commonService.update(user); private void setMailAccount(User user) MailA

47、ccount mailAccount = mailAccountService.getMailAccount(user.getId(); if (mailAccount != null) user.setMailAccount(mailAccount); mailManageService.connectReceive(mailAccount); ,代码的坏味道,过长方法 解决之道 提取方法 public ResponseBody int login(String username, String password, String checkcode, HttpSession session,

48、 HttpServletRequest request) if(!checkCode(session) return 0; User user = null; if(!checkUser(user) return 1; if(! checkPassword(password,user) return 2; saveLoginInfo(user); setMailAccount(user); setUser(user); return 3; ,代码的坏味道,过长方法,代码的坏味道,过长方法,代码的坏味道,过大类 public class CompanyController extends UploadController JSONMessage save(CompanyName company) JSONMessage collectCompany(Long companyId) JSONMessage findCompany(String companyName)

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 其他


经营许可证编号:宁ICP备18001539号-1