如何写好的代码.ppt

上传人:sccc 文档编号:5474832 上传时间:2023-07-11 格式:PPT 页数:70 大小:962.55KB
返回 下载 相关 举报
如何写好的代码.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 Golding编程的

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

3、lse);List organizations=orgDataService.getOrgAll();List employees=orgDataService.getEmployeePositionAll(000001);/temp2.引入bug隐患commonService.update(user);MailAccount mailAccount=mailAccountService.getMailAccount(userId);if(mailAccount!=null)user.setMailAccount(mailAccount);mailManageService.connectRe

4、ceive(mailAccount);setUser(user);setCurLanguage(zh_CN);,代码的坏味道,hard codeString replayInfo=-,代码的坏味道,hard code3.难以扩展if(!filepath.endsWith(.jpg),代码的坏味道,hard code4.解决之道.引入常量 List employees=orgDataService.getEmployeePositionAll(000001);/tempprivate static final String BOSS_EMPLOYEE_CODE=000001;List emplo

5、yees=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.se

6、tInvalid(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;elsefromTo=2;resumeJob.setInvite(1);resumeJob.setFromTo(2);resumeJob.set

7、Reading(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.可以允许的

8、数字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.解决之道使用枚举类

9、型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=OperationT

10、ype.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-companyIdStrL

11、ength;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.

12、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.getP

13、ersonal(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.getSelfRecomme

14、nds(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,trainningSer

15、vice.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,res

16、umeService.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).

17、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,re

18、sumeService.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.addObj

19、ect(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);m

20、odel.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.getPract

21、ices(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*/RequestMappin

22、g(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_

23、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+,file

24、Path:+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,m

25、ethod=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.setCharacterEn

26、coding(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.connectS

27、erver();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();fina

28、lly 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?remunerat

29、ionList.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);

30、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.sa

31、ve(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 co

32、rpIdx=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 companyIdStrLeng

33、th=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

34、(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);

35、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(jobS

36、etting,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

37、.put(companyId,company.getId();companyInfo.put(companyName,company.getCompanyName();companyInfo.put(logoPath,company.getLogoPath();companys.add(companyInfo);,代码的坏味道,重复代码Jodd APIpublic void bean2Map(Object bean,String properties)Map companyInfo=new HashMap();for(String property:properties)companyInfo

38、.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,Stri

39、ng 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.get

40、Id();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.setBeforeOpe

41、rateTime(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(

42、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.getBeforeOper

43、ateTime()=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!=n

44、ull)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)retur

45、n 1;if(!checkPassword(password,user)return 2;saveLoginInfo(user);setMailAccount(user);setUser(user);return 3;,代码的坏味道,过长方法,代码的坏味道,过长方法,代码的坏味道,过大类public class CompanyController extends UploadControllerJSONMessage save(CompanyName company)JSONMessage collectCompany(Long companyId)JSONMessage findCompan

46、y(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 removeCompanyCon

47、tact(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,Lo

48、ng 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

49、,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

50、(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

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

当前位置:首页 > 建筑/施工/环境 > 农业报告


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号