• 蛙蛙推荐:笨办法提高代码质量


    软件中的大多Bug都与各种低级错误有关,而大多低级错误是靠测试测不出来的,更多的需要Code Review来发现问题。

    培养好的习惯,不靠任何假设编程,可以先从写好每个函数开始,我想用注释驱动来提醒自己经常Review每个函数。

    以下是我拟定的Code Review Comments:

    /* ### Code Review
     * ### Reviewer: wawa
     * ### Last Review Date: 2013-01-29
     *
     * - todo: input review
     * - todo: output review 
     * - todo: exception review 
     * - todo: null reference review
     * - todo: out of bounds review 
     *
     * */

    每个函数都加上这么一段注释,某项review通过后把todo改成done,如果代码修改后要重新review,并修改Last Review Date。

    这么玩肯定会很麻烦,但我的理念就是代码写的越慢越好,通过Check List来强制对代码进行某些思考,从而慢慢养成习惯。

    比如下面这段用户登录的代码。

    function login(username, password){
        var account = accountDAO.getAccount();
        if (account['password'] == password){
            return {code:200, message:'login success.'} 
        }else{
            return {code:403, message:'login faild.'} 
        }
    }

    很明显有很多问题,然后经过review,修改如下

    /* ### Code Review
     * ### Reviewer: wawa
     * ### Last Review Date: 2013-01-29
     *
     * - done: input review
     * - done: output review 
     * - done: exception review 
     * - done: null reference review
     * - done: out of bounds review 
     *
     * */
    function login(username, password){
        if (username === null || password === null 
            || username === '' || password === ''){
            return {code:400, message: 'input invalid'};
        }
    
        try{
            var account = accountDAO.getAccount();
            if (account === null){
                return {code:404, message: 'account not found'};
            }
        }
        catch(err){
            return {code:500, message: 'server error'};
        }
    
        if (!('password' in account)){
            return {code:500, message: 'server error'};
        }
        if (account['password'] == password){
            return {code:200, message:'login success.'} 
        }else{
            return {code:401, message:'login faild.'} 
        }
    }

    第一步就先做这几个基本的检查吧。

    1. input review: 输入检查,主要是参数有效性检查,安全检查
    2. output review:输出检查,对返回值进行契约检查,比如一个计算工资的函数,不能返回负数;
    3. exception review: 异常检查,分两方面
      1. 一是有可能你调用的某个方法会抛出异常,你是要捕捉,还是继续往上抛;
      2. 二是你这个函数有可能会抛出什么异常,都要进行思考,做到心中有数;
    4. null reference review: 空引用检查,你得到的某个变量,是否可能为空,空引用是最常见的低级错误;
    5. out of bounds review: 索引越界检查,对数组和字典的使用,都有可能造成索引越界;
  • 相关阅读:
    sql server 索引总结一
    公用表表达式(CTE)
    解决Setting property 'source' to 'org.eclipse.jst.jee.server的问题
    python测试开发django-2.templates模板与html页
    python测试开发django-1.开始hello world!
    pytest文档28-重复执行用例(pytest-repeat)
    pytest文档27-pytest分布式执行(pytest-xdist)
    pytest文档26-运行上次失败用例(--lf 和 --ff)
    pytest文档25-conftest.py作用范围
    python接口自动化11-post传data参数案例
  • 原文地址:https://www.cnblogs.com/onlytiancai/p/2881170.html
Copyright © 2020-2023  润新知