考慮有這樣的一個函數(shù),這個函數(shù)會異步地連接到一個IPv4地址的TCP端口。我們通過例子來看文檔怎么寫:
/*
* Make a TCP connection to the given IPv4 address. Arguments:
*
* ip4addr a string representing a valid IPv4 address
*
* tcpPort a positive integer representing a valid TCP port
*
* timeout a positive integer denoting the number of milliseconds
* to wait for a response from the remote server before
* considering the connection to have failed.
*
* callback invoked when the connection succeeds or fails. Upon
* success, callback is invoked as callback(null, socket),
* where `socket` is a Node net.Socket object. Upon failure,
* callback is invoked as callback(err) instead.
*
* This function may fail for several reasons:
*
* SystemError For "connection refused" and "host unreachable" and other
* errors returned by the connect(2) system call. For these
* errors, err.errno will be set to the actual errno symbolic
* name.
*
* TimeoutError Emitted if "timeout" milliseconds elapse without
* successfully completing the connection.
*
* All errors will have the conventional "remoteIp" and "remotePort" properties.
* After any error, any socket that was created will be closed.
*/
function connect(ip4addr, tcpPort, timeout, callback)
{
assert.equal(typeof (ip4addr), 'string',
"argument 'ip4addr' must be a string");
assert.ok(net.isIPv4(ip4addr),
"argument 'ip4addr' must be a valid IPv4 address");
assert.equal(typeof (tcpPort), 'number',
"argument 'tcpPort' must be a number");
assert.ok(!isNaN(tcpPort) && tcpPort > 0 && tcpPort < 65536,
"argument 'tcpPort' must be a positive integer between 1 and 65535");
assert.equal(typeof (timeout), 'number',
"argument 'timeout' must be a number");
assert.ok(!isNaN(timeout) && timeout > 0,
"argument 'timeout' must be a positive integer");
assert.equal(typeof (callback), 'function');
/* do work */
}
這個例子在概念上很簡單,但是展示了上面我們所談?wù)摰囊恍┙ㄗh:
參數(shù),類型以及其它一些約束被清晰的文檔化。
這個函數(shù)對于接受的參數(shù)是非常嚴(yán)格的,并且會在得到錯誤參數(shù)的時候拋出異常(程序員的失誤)。
可能出現(xiàn)的操作失敗集合被記錄了。通過不同的”name“值可以區(qū)分不同的異常,而”errno“被用來獲得系統(tǒng)錯誤的詳細(xì)信息。
異常被傳遞的方式也被記錄了(通過失敗時調(diào)用回調(diào)函數(shù))。
返回的錯誤有”remoteIp“和”remotePort“字段,這樣用戶就可以定義自己的錯誤了(比如,一個HTTP客戶端的端口號是隱含的)。
這看起來像是給一個很容易理解的函數(shù)寫了超過大部分人會寫的的超長注釋,但大部分函數(shù)實際上沒有這么容易理解。所有建議都應(yīng)該被有選擇的吸收,如果事情很簡單,你應(yīng)該自己做出判斷,但是記?。河檬昼姲杨A(yù)計發(fā)生的記錄下來可能之后會為你或其他人節(jié)省數(shù)個小時。
更多建議: