zoukankan      html  css  js  c++  java
  • 读书笔记之《The Art of Readable Code》part 1

    《The Art of Readable Code》
    - Dustin Boswell, Trevor Foucher    O'Reilly出版

    整体认知:
    这本书写得很好,每一章后面的总结,很简练,很到位。


    问题:
    什么样的代码才是可读性好的代码?
    - 书中给出的衡量标准是,让新手读你的代码,看从开始读到完全理解所花的时间,时间越少说明代码可读性越好。
       这里的新手,也指之后需要维护你写的代码的同事,或者几个月之后重新审视代码的你自己。

    什么样的命名是好的命名呢?
     - 名字包含所需的信息,新手看了很容易理解。

    如何才能取个好的名字呢?
    - 具体来说有:
     1. Use specific words
        a. GetPage(url) → FetchPage() or DownloadPage()
        get太普通,并没有太多具体意思。
        b. int BinaryTree::Size();  → Height() or NumNodes() or MemoryBytes()
     2. Avoid generic names, like tmp and retval,
     3. Prefer concrete names over abstract names
        e.g.  name a fun which test whether the server can linsten on a given TCP/IP port
        ServerCanStart()  -- NG
        CanListenOnPort() -- Good

      e.g. 定义了一个C++宏,目的是禁止类重载拷贝构造函数和复制构造函数。
        #define DISALLOW_EVIL_CONSTRUCTORS(ClassName)   -- NG
            ClassName(const ClassName&);
            void operator=(const ClassName&);       

        #define DISALLOW_COPY_AND_ASSIGN(ClassName) ... -- Good

        e.g. 一个命令行程序,在本地跑的时候加上一个参数能够输出额外的debug信息,但是耗时间,
       在服务器上跑时,就不加上参数。
        --run-locally  -- NG
        --extra_logging    --Good
        --use_local_database --Good
        4. attach important details, 例如一个变量如果是表示时间并且是毫秒单位,可以加上_ms后缀
      给一个待处理的字符串,加上raw_前缀等。
        5. 变量名的长短根据可见范围来定。简单的循环变量用i,j,k就可以了,但是函数的变量或类的变量
          要考虑包含更多信息。
        6.利用语言特有的约定。比如大写、下划线和连字符分别在什么情况下用,在部门里统一即可。
           例如: html里class用-连接,id用_连接。再有js里jquery变量,加上前缀$等。

    如何才能取个不让人误解的名字? (chap 2)

        0. Think about what other meanings could someone interpret from this name?
        results = Database.all_objects.filter("year <= 2011")
         -> select()     ==> to pick out
            exclude() (my exp: filterOut()) ==> to get rid of
        eg.

        def Clip(text, length):
            ...
        -> Truncate(text, length) -> Truncate(text, max_chars)

        1. Prefer min & max for (inclusive) limits
        e.g.
        CART_TOO_BIG_LIMIT = 10
        if shopping_car.num_items() >= CART_TOO_BIG_LIMIT [bug, should be >]
             Error("Too many items in cart.")
        -> MAX_ITEMS_IN_CART = 10

        2. prefer first & last for inclusive ranges -> [first, last]
        e.g.
        print integer_range(start=2,stop=4)   [bad]
        print integer_range(first=2,last=4)   [good]
        set.PrintKeys(first="Bart", last="Maggie")

        comment: unlike stop, word last is clearly inclusive

        prefer begin & end for inclusive/exclusive ranges -> [begin, end)
        e.g. PrintEventsInRange("OCT 16 12:00am","OCT 17 12:00am")

        3. naming booleans
        e.g.
        bool read_password = true;  [bad, ambiguous]

        -> bool need_password;
           bool user_is_authenticated;

        comment: In general, adding words like is, has, can, or should can make booleans more clear

        e.g. SpaceLeft()
        -> HasSpaceLeft()

        It's best to avoid negated terms in a name.

        bool disable_ssl = false;
        -> bool use_ssl = true;

        4. Matching expectations of users

        e.g. get*()  用户的预期是简单操作,获取某个变量的值

        double getMean() {   [bad]
            ...
        }

        -> computeMean()   [good, 听起来像个更重更耗时的操作]

        e.g. list::size()

        void ShrinkList(list<Node>& list, int max_size) {
            while (list.size() > max_size) { // bug, O(n)
                FreeNode(list.back());
                list.pop_back();
            }
        }

    怎么样的布局是美的呢?如何利用(空格/换行/注释)使得代码更易读? (Chap 4)

        0. 总的方法
            - consistent layout
            - make similar code look similar
            - group related lines
        一些示例如下:
    e.g.1 bad

    e.g.1 good

    e.g.1 better


        1. column alignment
        2. pick a meaningful order, use it consistently
          - in the order of <input> fields in HTML
          - "most important" -> "least important"
          - alphabetically
        3. organize declarations into blocks
        e.g.2 bad

    e.g.2 good


        4. break code into "paragraph"
        e.g.3bad

    e.g. 3 good

        5. personal style vs consistency
        e.g. 有些人喜欢将方法或类的起始括号放在一行,有人喜欢另起一行
            正确做法是遵从project的规定

        idea: Consistent style is more important than the "right" style


    如何利用注释使代码更可读?(chap 5)

        0.注释的作用, 帮助读者尽可能多的知道作者做了什么
        - know what not to comment
        - record your thoughts as you code
        - put yourself in the reader's shoes, to imagine what they'll need to know

        1. what not to commet
        读注释需要时间; 注释需要占用屏幕空间,所以尽可能避免无用注释(一眼就能看出来的, "what/how")
        good code > bad code + good comments

        2. record your thoughts
        - Include "Director Commentary"
        - Comment the flaws in your code
           TODO: / FIXME: / HACK: / XXX:
        - comment on your constants
            The "story" for how a constant got its value

        3. put yourself in the Reader's shoes

        Think ahead about a function/class
        - What is surprising about this code?
        - How might it be misused?

    e.g. 5.1.2 no comment cause question


    e.g. 5.1.2 solution


    e.g. 5.1.3 sample
       

    e.g. 5.1.4 sample


        4. summary comments

    e.g. 5.1.5 sample of summary comments


        It's especially helpful to have summary comments in longer functions where there are a few large "chunks" inside

    e.g. 5.1.6 sample of summary comments


    知道了注释写什么之后如何写更好呢?(chap6)

        0. comments should have a high information-to-space ratio.













  • 相关阅读:
    记第一次为开源代码报漏洞
    入职第三周——总结前两周学习内容
    入职一星期之感想
    毕业季之礼
    基于mint-ui的移动应用开发案例二(项目搭建)
    基于mint-ui的移动应用开发案例一(简介)
    工作笔记一——杂项
    微信小程序实战小小应用——豆瓣电影
    React学习之坑(二)- 基础入门
    React学习笔记(一)- 环境搭建
  • 原文地址:https://www.cnblogs.com/xianzhon/p/6242819.html
Copyright © 2011-2022 走看看