party_bid 项目之 重构

1.圈复杂度(Cyclomatic Complexity)

  是一种代码复杂度的衡量标准。它可以用来衡量一个模块判定结构的复杂程度,数量上表现为独立现行路径条数,也可理解为覆盖所有的可能情况最少使用的测试用例数。圈复杂度大说明程序代码的判断逻辑复杂,可能质量低且难于测试和维护。程序的可能错误和高的圈复杂度有着很大关系。

  在之前的开发中,代码中的for循环和if - else if -else句随处可见,而且其中经常会嵌套另一层循环等,例如冒泡排序算法。这样就会使程序的圈复杂度提高,并且降低了程序的可维护性和健壮性。 

  在重构中,通过合并条件分支,合并后可用boolean变量来替换条件分支中的语句以及underscore取代for循环。例如:

  

function bid_result(priceLists,priceNumber)
{
    var count = _.chain(priceLists)
        .sortBy("price")
        .groupBy(function(price){
        return price.price;
    })
    _.map(count._wrapped, function (value,key) {
        priceNumber.push({'price': key, 'number': value.length,'value':value});
    })

    save_localStorage("localStorage_bid_results",priceNumber);
}

function get_result(bid_results)
{
    return _.find(bid_results,function(list)
    {
        return list.number == 1;
    });
}

 2.面向对象编程

  javascript语言是基于原型的面向对象方式,对象依靠构造器constructor利用原型(prototype)构造出来的。在对数据进行增删改查等操作时,可以通过调用对象实例的方法来实现具体的操作,从而可以节省数据间的传送。  

function Activity(put)
{
    this.title = put,
    this.disabled = false,
    this.color = "",
    this.bid=0
}

//save
Activity.prototype.save = function () {
    var list = Activity.get_activities();
    list.unshift(this);
    save_localStorage("localEventsLists",list);
}

Activity.get_activities = function () {
    return JSON.parse(localStorage.getItem("localEventsLists")) || [];
};


 3.

猜你喜欢

转载自244346826.iteye.com/blog/1996972
今日推荐