漫談程序員(十八)淺談谷歌用戶體驗設計準則
556
2025-03-31
前言
本篇博文來自一次公司內部的前端分享,從多個方面討論了在設計接口時遵循的原則,總共包含了七個大塊。系鹵煮自己總結的一些經驗和教訓。本篇博文同時也參考了其他一些文章,相關地址會在后面貼出來。很難做到詳盡充實,如果有好的建議或者不對的地方,還望不吝賜教斧正。
一、接口的流暢性
好的接口是流暢易懂的,他主要體現如下幾個方面: 1. 簡單 操作某個元素的 css 屬性,下面是原生的方法:
1
document.querySelector('#id').style.color = 'red';
封裝之后
1
2
3
4
function a(selector, color) {
document.querySelector(selector).style.color = color
}
a('#a', 'red');
從幾十個字母長長的一行到簡簡單單的一個函數調用,體現了 api 設計原則之一:簡單易用。 2. 可閱讀性 a (‘#a’, ‘red’) 是個好函數,幫助我們簡單實用地改變某個元素,但問題來了,如果第一次使用該函數的人來說會比較困惑,a 函數是啥函數,沒有人告訴他。開發接口有必要知道一點,大多數人都是懶惰的(包括鹵煮自己),從顏色賦值這個函數來說,雖然少寫了代碼,但是增加了單詞字母的個數,使得它不再好記。每次做這件事情的時候都需要有映射關系: a—->color. 如果是簡單的幾個 api 倒是無所謂,但是通常一套框架都有幾十甚至上百的 api,映射成本增加會使得程序員哥哥崩潰。 我們需要的就是使得接口名稱有意義,下面我們改寫一下 a 函數:
1
2
function letSomeElementChangeColor(selector, color) {
document.querySelectorAll(selector, color).style.color = color; }
letSomeElementChangeColor 相對于 a 來說被賦予了現實語言上的意義,任何人都不需要看說明也能知道它的功能。 3. 減少記憶成本 我們剛剛的函數太長了,letSomeElementChangeColor 雖然減少了映射成本,有了語言上的意義,但是毫無疑問增加了記憶成本。要知道,包括學霸在內,任何人都不喜歡背單詞。不僅僅在此處,原生獲取 dom 的 api 也同樣有這個問題: document.getElementsByClassName; document.getElementsByName; document.querySelectorAll; 這些 api 給人的感覺就是單詞太長了,雖然他給出的意義是很清晰,然而這種做法是建立在犧牲簡易性和簡憶性的基礎上進行的。于是我們又再次改寫這個之前函數
1
2
3
function setColor(selector, color) {
xxxxxxxxxxxx
}
在語言意義不做大的變化前提下,縮減函數名稱。使得它易讀易記易用。 4. 可延伸 所謂延伸就是指函數的使用像流水一樣按照書寫的順序執行形成執行鏈條:
1
2
3
document.getElementById('id').style.color = 'red';
document.getElementById('id').style.fontSize = '12px';
document.getElementById('id').style.backgourdColor = 'pink';
如果我們需要實現像以上有強關聯性的業務時,用我們之前的之前的方法是再次封裝兩個函數 setFontSize, setbackgroundColor; 然后執行它們 setColor (‘id’, ‘red’);setFontSiez (‘id’, ’12px’); setbackgroundColor (‘id’, ‘pink’); 顯然,這樣的做法沒有懶出境界來;id 元素每次都需要重新獲取,影響性能,失??;每次都需要添加新的方法,失?。?每次還要調用這些方法,還是失敗。下面我們將其改寫為可以延伸的函數 首先將獲取 id 方法封裝成對象,然后再對象的每個方法中返回這個對象:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function getElement(selector) {
this.style = document.querySelecotrAll(selector).style;
}
getElement.prototype.color = function(color) {
this.style.color = color;
return this;
}
getElement.prototype.background = function(bg) {
this.style.backgroundColor = bg;
return this;
}
getElement.prototype.fontSize = function(size) {
this.style.fontSize = size;
return this;
}
//調用
var el = new getElement('#id')
el.color('red').background('pink').fontSize('12px');
簡單、流暢、易讀,它們看起來就像行云流水一樣,即在代碼性能上得到了提升優化,又在視覺上悅目。后面我們會在參數里面講到如何繼續優化。 所以,大家都比較喜歡用 jquery 的 api,雖然一個 $ 符號并不代表任何現實意義,但簡單的符號有利于我們的使用。它體現了以上的多種原則,簡單,易讀,易記,鏈式寫法,多參處理。 nightmare:
1
2
3
document.getElementById('id').style.color = 'red';
document.getElementById('id').style.fontSize = '12px';
document.getElementById('id').style.backgourdColor = 'pink';
dream:
1
$('id').css({color:'red', fontSize:'12px', backgroundColor:'pink'})
二、一致性
1. 接口的一致性 相關的接口保持一致的風格,一整套 API 如果傳遞一種熟悉和舒適的感覺,會大大減輕開發者對新工具的適應性。 命名這點事:既要短,又要自描述,最重要的是保持一致性 “在計算機科學界只有兩件頭疼的事:緩存失效和命名問題” — Phil Karlton 選擇一個你喜歡的措辭,然后持續使用。選擇一種風格,然后保持這種風格。 Nightmare:
1
2
3
4
setColor,
letBackGround
changefontSize
makedisplay
dream:
1
2
3
4
setColor;
setBackground;
setFontSize
set.........
盡量地保持代碼風格和命名風格,使別人讀你的代碼像是閱讀同一個人寫的文章一樣。
三、參數的處理
1. 參數的類型 判斷參數的類型為你的程序提供穩定的保障
1
2
3
4
5
//我們規定,color接受字符串類型
function setColor(color) {
if(typeof color !== 'string') return;
dosomething
}
2. 使用 json 方式傳參 使用 json 的方式傳值很多好處,它可以給參數命名,可以忽略參數的具體位置,可以給參數默認值等等 比如下面這種糟糕的情況:
1
function fn(param1, param2...............paramN)
你必須對應地把每一個參數按照順序傳入,否則你的方法就會偏離你預期去執行,正確的方法是下面的做法。
1
2
3
4
5
6
7
8
function fn(json) {
//為必須的參數設置默認值
var default = extend({
param: 'default',
param1: 'default'
......
},json)
}
這段函數代碼,即便你不傳任何參數進來,他也會預期運行。因為在聲明的時候,你會根據具體的業務預先決定參數的缺省值。
四、可擴展性
軟件設計最重要的原則之一:永遠不修改接口,而是去擴展它!可擴展性同時會要求接口的職責單一,多職責的接口很難擴展。 舉個栗子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//需要同時改變某個元素的字體和背景
// Nightmare:
function set(selector, color) {
document.querySelectroAll(selector).style.color = color;
document.querySelectroAll(selector).style.backgroundColor = color;
}
//無法擴展改函數,如果需要再次改變字體的大小的話,只能修改此函數,在函數后面填加改變字體大小的代碼
//Dream
function set(selector, color) {
var el = document.querySelectroAll(selector);
el.style.color = color;
el.style.backgroundColor = color;
return el;
}
//需要設置字體、背景顏色和大小
function setAgain (selector, color, px) {
var el = set(selector, color)
el.style.fontSize = px;
return el;
}
以上只是簡單的添加顏色,業務復雜而代碼又不是你寫的時候,你就必須去閱讀之前的代碼再修改它,顯然是不符合開放 - 封閉原則的。修改后的 function 是返回了元素對象,使得下次需要改變時再次得到返回值做處理。 2.this 的運用 可擴展性還包括對 this 的以及 call 和 apply 方法的靈活運用:
1
2
3
4
5
6
7
8
9
function sayBonjour() {
alert(this.a)
}
obj.a = 1;
obj.say = sayBonjour;
obj.say();//1
//or
sayBonjour.call||apply(obj);//1
五、對錯誤的處理
1. 預見錯誤 可以用 類型檢測 typeof 或者 try…catch。 typeof 會強制檢測對象不拋出錯誤,對于未定義的變量尤其有用。 2. 拋出錯誤 大多數開發者不希望出錯了還需要自己去找帶對應得代碼,最好方式是直接在 console 中輸出,告訴用戶發生了什么事情。我們可以用到瀏覽器為我們提供的 api 輸出這些信息:console.log/warn/error。你還可以為自己的程序留些后路: try…catch。
1
2
3
4
5
6
7
8
9
10
11
12
13
function error (a) {
if(typeof a !== 'string') {
console.error('param a must be type of string')
}
}
function error() {
try {
// some code excucete here maybe throw wrong
}catch(ex) {
console.wran(ex);
}
}
六、可預見性
可預見性味程序接口提供健壯性,為保證你的代碼順利執行,必須為它考慮到非正常預期的情況。我們看下不可以預見的代碼和可預見的代碼的區別用之前的 setColor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//nighware
function set(selector, color) {
document.getElementById(selector).style.color = color;
}
//dream
zepto.init = function(selector, context) {
var dom
// If nothing given, return an empty Zepto collection
if (!selector) return zepto.Z()
// Optimize for string selectors
else if (typeof selector == 'string') {
selector = selector.trim()
// If it's a html fragment, create nodes from it
// Note: In both Chrome 21 and Firefox 15, DOM error 12
// is thrown if the fragment doesn't begin with <
if (selector[0] == '<' && fragmentRE.test(selector))
dom = zepto.fragment(selector, RegExp., context), selector = null
// If there's a context, create a collection on that context first, and select
// nodes from there
else if (context !== undefined) return $(context).find(selector)
// If it's a CSS selector, use it to select nodes.
else dom = zepto.qsa(document, selector)
}
// If a function is given, call it when the DOM is ready
else if (isFunction(selector)) return $(document).ready(selector)
// If a Zepto collection is given, just return it
else if (zepto.isZ(selector)) return selector
else {
// normalize array if an array of nodes is given
if (isArray(selector)) dom = compact(selector)
// Wrap DOM nodes.
else if (isObject(selector))
dom = [selector], selector = null
// If it's a html fragment, create nodes from it
else if (fragmentRE.test(selector))
dom = zepto.fragment(selector.trim(), RegExp., context), selector = null
// If there's a context, create a collection on that context first, and select
// nodes from there
else if (context !== undefined) return $(context).find(selector)
// And last but no least, if it's a CSS selector, use it to select nodes.
else dom = zepto.qsa(document, selector)
}
// create a new Zepto collection from the nodes found
return zepto.Z(dom, selector)
}
七、注釋和文檔的可讀性
一個最好的接口是不需要文檔我們也會使用它,但是往往接口量一多和業務增加,接口使用起來也會有些費勁。所以接口文檔和注釋是需要認真書寫的。注釋遵循簡單扼要地原則,給多年后的自己也給后來者看:
1
2
3
4
5
6
7
8
9
10
//注釋接口,為了演示PPT用
function commentary() {
//如果你定義一個沒有字面意義的變量時,最好為它寫上注釋:a:沒用的變量,可以刪除
var a;
//在關鍵和有歧義的地方寫上注釋,猶如畫龍點睛:路由到hash界面后將所有的數據清空結束函數
return go.Navigate('hash', function(){
data.clear();
});
}
最后
推薦 markdown 語法書寫 API 文檔,github 御用文檔編寫語法。簡單、快速,代碼高亮、話不多說上圖 鹵煮在此也推薦幾個在線編輯的網站。諸君可自行前往練習使用。 https://www.zybuluo.com/mdeditor http://mahua.jser.me/
參考博文
前端頭條 - javascript 的 api 設計原則 原文:http://www.cnblogs.com/constantince/p/5580003.html
API JavaScript
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。