如何写好的代码.ppt_第1页
如何写好的代码.ppt_第2页
如何写好的代码.ppt_第3页
如何写好的代码.ppt_第4页
如何写好的代码.ppt_第5页
已阅读5页,还剩65页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

如何写好的代码,数融信息技术有限公司 冯国平,什么是好的代码,问题: 什么是好的代码? 什么是坏的代码?,什么是好的代码,代码要人能够读懂-Martin Fowler 任何一个傻瓜都能写出机器能懂的代码,好的程序员应该写出人能读懂的代码。 -Martin Flowler 重构,什么是好的代码,代码是给人看的-Harold Abelson 程序必须是写给人看的,仅仅偶尔才在机器上执行。 -Harold Abelson等人,什么是好的代码,程序是人-Steve McConnell 编写程序首先为人,其次为计算机。 -Steve McConnell,什么是好的代码,写烂代码是危险的-Martin Golding 编程的时候,总是想着那个维护你代码的人是一个只读你住在什么地方的、有着暴力倾向的精神病患者。 -Martin Golding,什么是好的代码,结论 好的代码有很多评价标准,但最重要的标准是 “易于理解,人能读懂!”,代码的坏味道,什么是代码的坏味道 是一个形象的比喻,由Martin Flower提出。 代码坏味道:是指在代码之中潜在问题的警示信号。 并非所有的坏味道所指示的确实是问题,但是对于绝大多数坏味道,均很有必要加以查看,并作出相应的修改。,代码的坏味道,hard code 1.读不懂 qps.add(qpbInvalid); getMulQueryParaBeans(“status”, “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(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 private 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) errorStr = “图片宽高不能超过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.getRecommendOrDeliver().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.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 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.removeLinkman(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) 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(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.saveOrUpdate(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(“jobTarget“,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.addObject(“educationExperinces“, educationService.findbyResumeId(id); model.addObject(“jobExperiences“, jobExperiencesList); model.addObject(“projectExperiences“, projectService.findbyResumeId(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“, resumeService.getAttachments(id); model.addObject(“privateSpace“, resumeService.getPrivateSpace(id); model.addObject(“privateAttachments“, resumeService.getPrivateAttachments(id);,代码的坏味道,重复代码 model.addObject(“printColumns“, resumeService.getPrintColumns(id); model.addObject(“basicData“, basicDataService.getStaticDataByCodeTypeAndLanguage(resumeService.get(id).getLanguage(), RESUME_BASICDATA_CODE); model.addObject(“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(“jobTarget“, jobTargetMap); model.addObject(“languages“, resumeService.getLanguages(id); model.addObject(“languageAchieve“, resumeService.getLanguageAchieve(id); model.addObject(“selfRecommends“, resumeService.getSelfRecommends(id); model.addObject(“educationExperinces“, educationService.findbyResumeId(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“, resumeService.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); model.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“,resumeService.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 (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(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.error(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 fileName, 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/html;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 input = 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(); 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“, 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.size() = 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.解决之道 提取方法 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); 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); 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 = new 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.saveOrUpdate(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); 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.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(); companyInfo.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.getProperty(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 password, 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; /待删除 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.getBeforeOperateTime() = 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.setMailAccount(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(); 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) MailAccount 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, 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) JSONMessage findOtherCompany(String companyName, Long companyIdOfJob) public ModelAndView getCompanyByCompanyId(Long id) public ModelAndView getCompany() JSONMessage saveCompany(Company company) JSONMessage saveCompanyContact(CompanyContact companyContact) JSONMessage removeCompanyContact(CompanyContact companyContact) JSONMessage getCompanyMap(Long companyId, Long id, Long linkman) JSONMessage saveCompanyMap(CompanyMap companyMap) ,代码的坏味道,过大类 JSONMessage getCompanyMap(Long id) public ModelAndView getFormMap(Long id) public void uploadPhoto(RequestParam(“file“) CommonsMultipartFile file, Long id, HttpServletResponse response) public void showPhoto(String photoid, HttpServletResponse response) private void showLogoNotGif(String filepath, FTPUtil ftpUtil, HttpServletResponse response) throws IOException public ModelAndView showRecommend() public ModelAndView showJobList(PJob pJob, Integer pageNo, Long curResumeId) Boolean desployTask(String empIdx, String corpIdx, Long resumeIdx, Long jobIdx, String jobName, String jobDept, String jobCompName, String userCorpIdx, String opinion, String fileName, Integer fileSize, String filePath, String proxyUrl, Integer master, Integer flowType) public ModelAndView report(Long companyId) throws UnsupportedEncodingException public void uploadComment(RequestParam(“file“) CommonsMultipartFile file,HttpServletResponse response) ,代码的坏味道,过大类 解决之道 合并方法 JSONMessage findCompany(String companyName) JSONMessage findOtherCompany(String companyName, Long companyIdOfJob) public ModelAndView getCompanyByCompanyId(Long id) public ModelAndView getCompany() JSONMessage save(CompanyName company) JSONMessage saveCompany(Company company) 抽取出通用方法 public void uploadPhoto(RequestParam(“file“) CommonsMultipartFile file,Long id, HttpServletResponse response) public void showPhoto(String photoid, HttpServletResponse response) public void uploadComment(RequestParam(“file“) CommonsMultipartFile file,HttpServletResponse response) private void showLogoNotGif(String filepath, FTPUtil ftpUtil,HttpServletResponse response) throws IOException 抽象到父类去 这里没有示例。,代码的坏味道,过多参数 public CompanyContact setLinkman(Long companyId, Long id, Long linkman) public CompanyContact removeLinkman(Long companyId, Long id, Long linkman) public Pager findJobsComment(long userId, Long jobId,Integer type, Integer pageNo,Integer w) public List findJobList(Long userId, Long companyId, Long positionId) public FavoritesJobUser getFavorites(String name1,String name2,String name3,Long id1,Long id2,Integer type) public Pager findMyResumeComments(final Long userId, final Long resumeId,final Integer type,final Integer pageNo) public void saveJobDeliver(JobDeliver jobDeliver, Long companyIds, Long resumeIds, Long userId) public FavoritesJobUser getFavorites(String name1,String name2,String name3,String name4,Long id1,Long id2,Integer type,Integer fromTo) public Pager findMyResu

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论