编程提示经验

一 基础部分
Introduction
I assume you are downloading some source code from time to time. You can learn a lot about a programmer while looking at his source code. There are some tips to help you write clear and effective code. So let's skip this boring introduction and go strait to the article!


Some tips
When naming a variable or a function, try to choose a significant name to help you (and your co-workers) understand the code. You can also use Hungarian notation.


Check the following code. Can you understand what it does?


a=Func1();
b=Func2();
if (a<b)
{
    if (!Func3())
    {
        Func4(1);
        return;
    }
    Func5(2);
}
Now let's write it again:


dtLastBackup=GetLastBackupDate();
dtCurrent=GetCurrentDate();
if (dtLastBackup<dtCurrent)
{
    if (!DoBackup())
    {
        ErrorMsg(IDS_ERRORBACKUP);
        return;
    }
    MessageBox(IDS_BACKUPSUCCEEDED);
}
Now we can understand the code. It is also a good idea to prefix member variables and global variables.


g_szPath=GetPath();
m_nCount=0;
Here we can understand immediately that g_szPath is a global string variable while m_nCount is an integer member variable.


Use uppercase in each word of a variable/name: Use "GetPathString" instead of "getpathstring".


Try to avoid using global variables and static functions. Use them only when necessary. Use member variables instead.


Add a comment to each major function and each block in your code. This way you and your co-workers can understand what is the purpose of a block/function.


Try to write "beautiful" code to be able to understand it.


for (int y=0;y<20;y++) 
  {for (x=0;x<20;x++) cout<<"x";cout<<"\n";}
for (int y=0;y<20;y++)
{
    for (x=0;x<20;x++)
        cout<<"x";
    cout<<"\n";
}
Try to use objects when you need to write initialization code. This way you won't forget to release memory. You can also use smart pointers instead of regular ones.


For example, you can write a class to wrap a database object, so you won't forget to close it. It will be closed automatically when the object is being destroyed.


class DBClass
{
protected:
    DB m_db;
public:
    ~DBClass()
    {
        Close();
    }
    bool Open();
    bool Close();
    DB operator->()
    {
        return m_db;
    }
};


void InsertTable(const char *szTableName)
{
    DBClass db;
    if (db.Open())
        db->Insert(szTableName);
}
Use resources for strings and macros/enums for integers. This way you won't have to follow all your code while changing it.


void ResetBoard(char pBoard[20][20])
{    // Suppose you want to switch to 25x25 board???
    for (int x=0;x<20;x++)
        for (y=0;y<20;y++)
            pBoard[y][x]=0;
}


// We can change the board size by changing only one line
#define BOARD_SIZE 20


void ResetBoard(char pBoard[BOARD_SIZE][BOARD_SIZE])
{
    for (int x=0;x<BOARD_SIZE;x++)
        for (y=0;y<BOARD_SIZE;y++)
            pBoard[y][x]=0;
}
Split your project into several files grouped by functionality. This way you can reuse your code easily. This is also useful when you follow your functions flow.


Use functions/macros instead of copy/paste your code. If you want to change something, you need change it only at one place.


ALWAYS handle errors/exceptions! Don't let your application crash due to an exception you forgot to catch.


Use TRACE/ASSERT as much as possible. They don't affect the release build but they can save you a lot of time while debugging.


Take some time to search for existing code instead of reinventing the wheel. For example: Suppose you want to download a file from the internet. Why open socket, parse headers (HTTP) and read the data when you can use existing objects to download files for you?


When using multithreading programming, don't forget to use critical section/mutex wherever we are using shared variables.


Use _T and text macros so you'll be able to build a Unicode version of your application. For example, use _tcslen/lstrlen instead of strlen.


Use sizeof and don't assume you know the size of your var iable/struct. This creates a portable code. Use fwrite(&nCount,sizeof(nCount)); instead of fwrite(&nCount,2);. An integer may be 2 bytes or 4 bytes long. Let the compiler define it.


Avoid using the heap. Try to use stack based variables. Don't be afraid of "stack overflow". The stack limit is equal to your memory limit. This way you can also avoid defragmentation of your memory.


Try to use standard libraries instead of others. Consider using STL instead of MFC when possible. This way you write a portable code.


Last but not least(最后一条但非常重要): BACKUP, BACKUP and BACKUP! You spend half a year working on your application just to find out that your HD crashed. Consider using CVS to track changes.(这一条我没做到,对于重要的资料,应该保存两份,自己一份,服务器上一份,明天就备份去!妈的!)


These are some basic tips. I am sorry for my poor English but I hope you can understand it anyway. If you have any other tips, you can send me and I'll add it to the article.


二 中级部分
1. Code for human consumption(消费)
It is one of the most pervasive(adj.普遍的) misunderstandings in computing that the source code is for the computer's consumption. Computers work with low-level binary code, a series of impenetrable(adj.费解的) 1's and 0's or hexadecimal numbers, not the structured high level languages we code in. The reason that these languages were developed was to help the programmer.


In practice, coding for human consumption often means coding for clarity first, over efficiency and speed second.


2. Comment often and comment well
The comment is the extreme example of a language element for human consumption. Most compilers will strip(vt. 剥去) the comments from the executable program. The purpose of the comment is to tell you (and any future developer) what the program is intended to do. Write comments with this in mind - and avoid simply restating(vt.换一个方式叙述) the code.


Good comment: Disable button to prevent its activation. 
Bad comment: Set cmd = False 
A good indication that you have got the level of comment right: could someone understand what your program does if all but the comments were removed?


3. Layout code to increase legibility(n.易读性)
Just as it is important for an author to split a book into chapters and paragraphs that aid reading so it is important for the developer to consider the layout of the code and how that can aid readability of the code. In particular, any code branch (an IF..THEN...ELSE construction) and any code repetition (a WHILE...END WHILE construction) should be indented so that it is easy to see where they start and end.


4. Expect the unexpected and deal with it
Before you open a file, make sure that the file is present. Before you set focus to a control, make sure that the control is visible and enabled. Try to work out what conditions could cause your code to fail and test for them before they cause the program to fall over. Also use explicit data type conversion wherever possible.


5. Name your variables to aid readability
There are a number of strategies to variable naming. The key is to be consistent and to be as informative as possible. If you name a variable nMonth, you give the programmer extra information as to what that variable is expected to contain. I personally prefer the Hungarian notation style - but whichever style you use, consistency(n.一致性) is the key.


6. Keep your functions and subroutines simple
A function or subroutine should ideally only do one thing. One of the greatest sources of misunderstandings, in my experience, is a subroutine that does a number of different operations. This should be split into separate functions for each different thing it is doing, so that these in turn are easy to reuse, and the scope of a code change is easy to understand.


7. Scope(限制...的范围) functions and variables appropriately
Functions and variables that are only used in one module should not be visible outside that module. Variables that are only used in a function or subroutine should not be visible outside that function or subroutine. This prevents any use of a variable or function outside of where it makes sense to use it.
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值