聽說程序員最怕命名!這個 7-7k Star 的手冊能幫上忙

hey,我是不愛寫代碼的在在。

依稀記得曾經有人做過調查,在程序員的編程生涯中,最困難的事情,命名排行榜首!!!

那麼如何打敗命名呢?

我給你們帶來了一個寶藏開源項目 — Naming cheatsheet,現在已經 7.7k Star 了。

image

它可以教你如何便捷、輕鬆的進行命名。只要我們按照它的命名原則,就一定能取出極佳的變量 /  函數名。

下面我們來具體看看 naming-cheatsheet 提的一些建議以及 JavaScript 示例吧。

命名建議

1、命名變量和函數時,請使用英語。

不管咱們喜不喜歡英語,英語好不好,英語都是編程中的主要語言。通過英語編寫代碼,可以大大提高內聚性。

/* Bad 示例 */
const primerNombre = 'Gustavo'
const amigos = ['Kate''John']

/* Good 示例 */
const firstName = 'Gustavo'
const friends = ['Kate''John']

2、選擇一個命名約定並遵循它。

它可能是camelCasePascalCasesnake_case,或其他任何東西,只要它保持一致。

/* Bad 示例*/
const page_count = 5
const shouldUpdate = true

/* Good 示例*/
const pageCount = 5
const shouldUpdate = true

/* Good as well 示例*/
const page_count = 5
const should_update = true

3、並且遵守 SID 原則

/* Bad */
const a = 5 // "a" could mean anything
const isPaginatable = a > 10 // "Paginatable" sounds extremely unnatural
const shouldPaginatize = a > 10 // Made up verbs are so much fun!

/* Good */
const postCount = 5
const hasPagination = postCount > 10
const shouldPaginate = postCount > 10 // alternatively

4、避免過度縮寫

會降低代碼的可讀性。

/* Bad */
const onItmClk = () ={}

/* Good */
const onItemClick = () ={}

5、避免上下文重複

名稱不應與定義名稱的上下文重複。

class MenuItem {
  /* Method name duplicates the context (which is "MenuItem") */
  handleMenuItemClick = (event) ={ ... }

  /* Reads nicely as `MenuItem.handleClick()` */
  handleClick = (event) ={ ... }
}

6、名稱應反映預期的結果

/* Bad */
const isEnabled = itemCount > 3
return <Button disabled={!isEnabled} />

/* Good */
const isDisabled = itemCount <= 3
return <Button disabled={isDisabled} />

命名模式

A/HC/LC 模式

可以參考以下類似的模式來做命名:

prefix? + action (A) + high context (HC) + low context? (LC)

示例:

getUserMessages

動作(A):get;高背景(HC):User;低語境(LC): Messages

動作

函數名稱的動詞部分。最重要的部分是負責描述功能的作用。

  1. get:獲取

  2. set:聲明

  3. reset:重置

  4. fetch:請求一些數據

  5. remove:移除

  6. delete:徹底刪除

  7. compose:從現有數據創建新數據。通常適用於字符串,對象或函數。

  8. handle:處理一個動作。通常在命名回調方法時使用。

語境

要說明其可操作域是什麼,或至少是預期的數據類型。

/* 使用原語操作的純函數 */
function filter(list, predicate) {
  return list.filter(predicate)
}

/* 功能操作正好在柱 */
function getRecentPosts(posts) {
  return filter(posts, (post) => post.date === Date.now())
}

前綴  or  單複數

前綴用來增強變量的含義,如:is,has,should,min/max,prev/next

變量名稱是單數還是複數,取決於值的單數還是複數,如:friends,foods

如果你對項目感興趣的話,這裏放上 GitHub 地址:

https://github.com/kettanaito/naming-cheatsheet

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/jXom3aH_09PoDgrXikv3eQ