みーのぺーじ

みーが趣味でやっているPCやソフトウェアについて.Python, Javascript, Processing, Unityなど.

The Art of Readable Code を読了した

The Art of Readable Code を読了しました.

翻訳本はこちら.

まとめ

章ごとの内容を簡潔にまとめ,自分用に補足したものです.

Chapter 1. Code Should Be Easy to Understand

  • Code should be written to minimize the time it would take for someone else to understand it.

Chapter 2. Packing Information into Names

  • If you’re going to use a generic name like tmp, it, or retval, have a good reason for doing so.
  • Attach important details
    • size()NumNodes()
    • delaydelay_secs
    • limitmax_kbps
  • Use longer names for larger scopes.
  • Use capitalization, underscores, and so on in a meaningful way.

Chapter 3. Names That Can’t Be Misconstrued

  • A lot of English words are ambiguous when it comes to programming, such as filter, length, and limit.
  • When it comes to defining an upper or lower limit for a value, max and min are good prefixes to use.
    • MAX_ITEMS_IN_CART
  • For inclusive ranges, first and last are good.
    • set.PrintKeys(first="Bart", last="Maggie")
  • For inclusive/exclusive ranges, begin and end are best because they’re the most idiomatic.
  • When naming a boolean, use words like is and has to make it clear that it’s a boolean.
    • is_authenticated
  • Avoid negated terms.
    • disable_ssluse_ssl

Chapter 4. Aesthetics (美学)

  • Pick a meaningful order and use it consistently.

Chapter 5. Knowing What to Comment

  • Insights about why code is one way and not another (“director commentary”).
  • Flaws in your code, by using markers:
    • TODO: Stuff I haven’t gotten around to yet
    • FIXME: Known-broken code here
    • HACK: Admittedly inelegant solution to a problem
    • XXX: Danger! major problem here
  • The “story” for how a constant got its value.

Chapter 6. Making Comments Precise and Compact

  • Assign arguments by name
    • Connect(timeout = 10, use_encryption = False)
  • Keep your comments brief by using words that pack a lot of meaning.
    • caching layer: 読み書きがより早い保存領域にデータを一時的に保存しておく
    • canonicalize: 標準化する,正規化する
    • heuristic algorithm: 発見的アルゴリズム=アルゴリズムによらずに,蓄えた経験的な知識によって,幾つかの選択肢の中から最適なものを選択する手法
    • brute-force: 総当たり
    • naive solution: 経験豊かなプログラマーが最初に浮かぶ,シンプルな方法

Chapter 7. Making Control Flow Easy to Read

  • When writing a comparison, it’s better to put the changing value on the left and the more stable value on the right.
  • Nested code blocks require more concentration to follow along. Each new nesting requires more context to be “pushed onto the stack” of the reader. Instead, opt for more “linear” code to avoid deep nesting.
  • Returning early can remove nesting and clean up code in general. “Guard statements” (handling simple cases at the top of the function) are especially useful.
public boolean Contains(String str, String substr) {
    if (str == null || substr == null) return false;
    if (substr.equals("")) return true;

    ...
}

Chapter 8. Breaking Down Giant Expressions

  • Introduce “explaining variables” that capture the value of some large subexpression.
username = line.split(':')[0].strip()
if username == "root":
    ...
  • Rewrite a boolean expression in a cleaner way using De Morgan’s laws. if (!(a && !b)) turns into if (!a || b)).

Chapter 9. Variables and Readability

  • Eliminate intermediate result variables by handling the result immediately.
  • Reduce the scope of each variable.
  • Prefer write-once variables.

Chapter 10. Extracting Unrelated Subproblems (下位の問題)

  • Separate the generic code from the project-specific code.

Chapter 11. One Task at a Time

  • Do only one task at a time.
  • Some of the tasks might easily become separate functions (or classes). Others might just become logical “paragraphs” within a single function.

Chapter 12. Turning Thoughts into Code

  • Describe your program in plain English and use that description to help you write more natural code.

Chapter 13. Writing Less Code

  • Eliminate nonessential features from your product.
  • Rethink requirements to solve the easiest version of the problem that still gets the job done
  • Stay familiar with standard libraries by periodically reading through their entire APIs

Chapter 14. Testing and Readability

  • If your test fails, it should emit an error message that makes the bug easy to track down and fix.
  • Use the simplest test inputs that completely exercise your code.
  • Give your test functions a fully descriptive name so it’s clear what each is testing.
    • Test1()Test_<FunctionName>_<Situation>()

Chapter 15. Designing and Implementing a “Minute/Hour Counter”

  • Naive solution
  • Conveyor belt design
  • Time-bucketed design

読みやすいソースコードを作成する方法は,様々なウェブサイトに記載されていますが,断片的なので活用しにくいです.この本には,ある程度の規模以上のソフトウェアを作成するために注意すべきことが網羅されており,理解しやすかったです.

”Reduce the scope of each variable.” と本文で記載しているためか,本の構成もスコープが徐々に広がっていくように並べてあり,題名に違わず英文も読みやすかったです.