例子

2018-02-24 16:17 更新

考慮有這樣的一個(gè)函數(shù),這個(gè)函數(shù)會(huì)異步地連接到一個(gè)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 */
}

這個(gè)例子在概念上很簡單,但是展示了上面我們所談?wù)摰囊恍┙ㄗh:

  • 參數(shù),類型以及其它一些約束被清晰的文檔化。

  • 這個(gè)函數(shù)對(duì)于接受的參數(shù)是非常嚴(yán)格的,并且會(huì)在得到錯(cuò)誤參數(shù)的時(shí)候拋出異常(程序員的失誤)。

  • 可能出現(xiàn)的操作失敗集合被記錄了。通過不同的”name“值可以區(qū)分不同的異常,而”errno“被用來獲得系統(tǒng)錯(cuò)誤的詳細(xì)信息。

  • 異常被傳遞的方式也被記錄了(通過失敗時(shí)調(diào)用回調(diào)函數(shù))。

  • 返回的錯(cuò)誤有”remoteIp“和”remotePort“字段,這樣用戶就可以定義自己的錯(cuò)誤了(比如,一個(gè)HTTP客戶端的端口號(hào)是隱含的)。

  • 雖然很明顯,但是連接失敗后的狀態(tài)也被清晰的記錄了:所有被打開的套接字此時(shí)已經(jīng)被關(guān)閉。

這看起來像是給一個(gè)很容易理解的函數(shù)寫了超過大部分人會(huì)寫的的超長注釋,但大部分函數(shù)實(shí)際上沒有這么容易理解。所有建議都應(yīng)該被有選擇的吸收,如果事情很簡單,你應(yīng)該自己做出判斷,但是記?。河檬昼姲杨A(yù)計(jì)發(fā)生的記錄下來可能之后會(huì)為你或其他人節(jié)省數(shù)個(gè)小時(shí)。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)