写好代码的十个秘诀.ppt
- 【下载声明】
1. 本站全部试题类文档,若标题没写含答案,则无答案;标题注明含答案的文档,主观题也可能无答案。请谨慎下单,一旦售出,不予退换。
2. 本站全部PPT文档均不含视频和音频,PPT中出现的音频或视频标识(或文字)仅表示流程,实际无音频或视频文件。请谨慎下单,一旦售出,不予退换。
3. 本页资料《写好代码的十个秘诀.ppt》由用户(saw518)主动上传,其收益全归该用户。163文库仅提供信息存储空间,仅对该用户上传内容的表现方式做保护处理,对上传内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知163文库(点击联系客服),我们立即给予删除!
4. 请根据预览情况,自愿下载本文。本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
5. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007及以上版本和PDF阅读器,压缩文件请下载最新的WinRAR软件解压。
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 代码 十个 秘诀
- 资源描述:
-
1、110 Things You Can Do To Write Better Code写好代码的十个秘诀写好代码的十个秘诀林斌林斌Development ManagerMicrosoft Research,China2一流代码的特性 鲁棒-Solid and Robust Code 简洁-Maintainable and Simple Code 高效-Fast Code 简短-Small Code 共享-Re-usable Code 可测试-Testable Code 可移植-Portable Code一流一流代码代码3Why is this code bad?void MyGirlFriend
2、Func(CORP_DATA InputRec,int CrntQtr,EMP_DATA EmpRec,float EstimRevenue,float YTDRevenue,int ScreenX,int ScreenY,COLOR_TYPE newColor,COLOR_TYPE PrevColor,STATUS_TYPE status,int ExpenseType)int i;for(i=1;i100;i+)InputRec.revenuei=0;for(i=1;i100;i+)InputRec.expensei=CorpExpensei;UpdateCorpDatabase(EmpR
3、ec);EstimRevenue=YTDRevenue*4.0/(float)CrntQtr;NewColor=PreColor;Status=Success;if(ExpenseType=1)for(i=1;i12;i+)Profiti=Revenuei-Expense.Type1i;else if(ExpenseType=2)Profiti=Revenuei-Expense.Type2i;else if(ExpenseType=3)Profiti=Revenuei-Expense.Type3i;4Why is this code bad?void MyGirlFriendFunc(CORP
4、_DATA InputRec,int CrntQtr,EMP_DATA EmpRec,float EstimRevenue,float YTDRevenue,int ScreenX,int ScreenY,COLOR_TYPE newColor,COLOR_TYPE PrevColor,STATUS_TYPE status,int ExpenseType)int i;for(i=1;i100;i+)InputRec.revenuei=0;for(i=1;i100;i+)InputRec.expensei=CorpExpensei;UpdateCorpDatabase(EmpRec);Estim
5、Revenue=YTDRevenue*4.0/(float)CrntQtr;NewColor=PreColor;Status=Success;if(ExpenseType=1)for(i=1;i 200 lines!Study in 1986 on IBMs OS/360:the most error-prone routines=longer than 500 lines.Study in 1991 on 148,000-line of code:functions 2.4 times less expensive to fix than longer functions.Over 1400
6、 lines!14Look at these codes Lets look at these codes from our own projects:Small functions:Larger functions:Then look at those from Windows 2000 source tree:NT Kernel Mode Code:NT User Mode CPP File:NT User Mode Header File:152.取个好名字取个好名字-Use Naming ConventionsHungarian Notation Prefix-BaseTag-Name
7、Standard Prefix:p A pointer.CHAR*psz;rg An array.DWORD rgType;c A count of items.DWORD cBook;h A handle.HANDLE hFile;Standard“BaseTag”void -v int -iBOOL -f UINT -uiBYTE -b CHAR -chWCHAR -wch ULONG -ulLONG -l DWORD -dwHRESULT-hr fn -functionsz -NULL str USHORT,SHORT,WORD-wC+member variables start wit
8、h:m_Global variables start with:g_16Lets try these A flag indicates whether a C+object has been initialized:BOOL m_fInitialized;A Session ID:DWORD dwSessionID;A ref count in a C+object:LONG m_cRef;/skip the l A Pointer to BYTE buffer:BYTE*pbBuffer;A global logfile filename buffer:CHAR g_szLogFileMAX
9、_PATH;A pointer to a global logfile:CHAR*g_pszLogFile;173.凌波微步,未必摔跤-Evil gotos?Maybe Not Why goto is bad?Creates unreadable code Causes compiler to generate non-optimal code Why goto is good?Cleaner code Single entry,single exit Less duplicate code18Spot the gotosSTART_LOOP:If(fStatusOk)if(fDataAvai
10、able)i=10;goto MID_LOOP;else goto END_LOOP;else for(I=0;I 100;I+)MID_LOOP:/lots of code here goto START_LOOP;END_LOOP:19BAD gotos!START_LOOP:If(fStatusOk)if(fDataAvaiable)i=10;goto MID_LOOP;else goto END_LOOP;else for(I=0;I=0)return TRUE;34Spot the detectBOOL SomeProblem(USHORT x)while(-x=0)return T
11、RUE;Infinite loop!Unsigned never negative!35Spot the detectwcscpy(wcServerIpAdd,WinsAnsiToUnicode(cAddr,NULL);Note:WinsAnsiToUnicode is a private API which allocates a new UNICODE string given an ANSI string.36Spot the detectwcscpy(wcServerIpAdd,WinsAnsiToUnicode(cAddr,NULL);WinsAnsiToUnicode can re
12、turn NULL which will cause a program crashWinsAnsiToUnicode can return allocated memory which will cause a leak37A better versionLPWSTR tmp;tmp=WinsAnsiToUnicode(cAddr,NULL);if(tmp!=NULL)wcscpy(wcServerIpAdd,tmp);WinsFreeMemory(PVOID)tmp);else return(ERROR_NOT_ENOUGH_MEMORY);385.见招拆招,滴水不漏-Handle The
13、 Error Cases:They Will Occur!Common examples:Out of memory Exceptions being thrown Registry keys missing Networks going down This is the hardest code to test so it better be right!Dont fail in C+object constructor,you cant detect it!39Error cases(continued)In an error case,the code should Recover gr
14、acefully Get to a consistent state Clean up any resources it has allocated Let its caller know Interface should define and document the behavior(return status,throw exception)Code should adhere to that definition What not to do Ignore the error Crash Exit40Spot the detectCWInfFile:CWInfFile()m_plLin
15、es =new TPtrList();/.m_plSections =new TPtrList();/.m_ReadContext.posLine=m_plLines-end();.41Spot the detectCWInfFile:CWInfFile()m_plLines =new TPtrList();/.m_plSections =new TPtrList();/.m_ReadContext.posLine=m_plLines-end();.vMFCs operator new throws an exception causing a leak when out of memory4
16、2A better version?CWInfFile:CWInfFile()try m_plLines =new TPtrList();/.m_plSections =new TPtrList();/.m_ReadContext.posLine=m_plLines-end();.catch(.)if(m_plLines)delete m_plLines;if(m_plSections)delete m_plSections;43No!CWInfFile:CWInfFile()try m_plLines =new TPtrList();/.m_plSections =new TPtrList(
17、);/.m_ReadContext.posLine=m_plLines-end();.catch(.)if(m_plLines)delete m_plLines;if(m_plSections)delete m_plSections;44A better versionCWInfFile:CWInfFile():m_plLines(NULL),m_plSections(NULL)try m_plLines =new TPtrList();/.m_plSections =new TPtrList();/.m_ReadContext.posLine=m_plLines-end();.catch(.
18、)if(m_plLines)delete m_plLines;if(m_plSections)delete m_plSections;45But wait,there is moreCWInfFile:CWInfFile():m_plLines(NULL),m_plSections(NULL)try m_plLines =new TPtrList();/.m_plSections =new TPtrList();/.m_ReadContext.posLine=m_plLines-end();.catch(.)if(m_plLines)delete m_plLines;if(m_plSectio
19、ns)delete m_plSections;46Spot the defectClass foo private:CHAR*m_pszName;DWORD m_cbName;public:foo(CHAR*pszName);CHAR*GetName()return m_pszName;foo:foo(CHAR*pszName)m_pszName=(BYTE*)malloc(NAME_LEN);if(m_pszName=NULL)return;strcpy(m_pszName,pszName);m_cbName=strlen(pszName);47Spot the defectClass fo
20、o private:CHAR*m_pszName;DWORD m_cbName;public:foo(CHAR*pszName);CHAR*GetName()return m_pszName;foo:foo(CHAR*pszName)m_pszName=(BYTE*)malloc(NAME_LEN);if(m_pszName=NULL)return;strcpy(m_pszName,pszName);m_cbName=strlen(pszName);If malloc()fails,this code will crash:foo*pfoo=new foo(“MyName”);if(pfoo)
21、CHAR c=*(pfoo-GetName();48A better versionClass foo private:CHAR*m_pszName;DWORD m_cbName;public:foo();HRESULT Init(CHAR*pszName);foo:foo()m_cbName=0;m_pszName=NULL;HRESULT foo:Init(CHAR*pszName)HRESULT hr=S_OK;if(pszName)m_cbName=lstrlen(pszName);m_pszName=(CHAR*)malloc(m_cbName+1);if(m_pszName=NUL
22、L)hr=E_OUTOFMEMORY;return hr;strcpy(m_pszName,pszName);else hr=E_INVALIDARG;return hr;496.熟习剑法刀术,所向无敌-Learn Win32 API Seriously Learn Win32 APIs,from MSDN Why Win32 APIs?Well designed Well tested Easy to understand Improve performance dramatically Understand the ones you use,read the SDK doc in MSDN
展开阅读全文