SOFTWARE ENGINEERING/Art Of Readable Code

Ch3 Names That Can’t Be Misconstrued

파란실버라이트 2012. 11. 23. 10:48

1.Matching Expectations of Users

var ShrinkList = function (list, max_size) {

    while (list.size() > max_size) {
        FreeNode(list.back());
        list.pop_back();
    }

/*    The “bug” is that the author didn’t know that list.size() is an O(n) operation—it counts
    through the linked list node by node, instead of just returning a precalculated count, which
    makes ShrinkList() an O(n2) operation.*/


    //Had size() been named countSize() or countElements(), the same mistake would be less likely.
    while (list.countSize() > max_size) {
        FreeNode(list.back());
        list.pop_back();
    }


    return 0;

};

 

2.Prefer min and max for Limits

 

var euclidean_norm = function (v) {


    CART_TOO_BIG_LIMIT = 10
    if (shopping_cart.num_items() >= CART_TOO_BIG_LIMIT)
        Error("Too many items in cart.")


/*    A D V I C E
    The clearest way to name a limit is to put max_ or min_ in front of the thing being
    limited.*/

 

    MAX_ITEMS_IN_CART = 10
    if (shopping_cart.num_items() > MAX_ITEMS_IN_CART)
        Error("Too many items in cart.")

 

/*    print integer_range(start=2, stop=4)
      set.PrintKeys(first="Bart", last="Maggie")
    # Does this print [2,3] or [2,3,4] (or something else)?*/

    return 0;

};