2011-11-15 88 views
1

一個簡單的問題:哪種類型的函數參數或動態語言中的返回值的文檔是最好的方法?在每個函數定義之後添加註釋?動態類型語言中的文檔

回答

1

約定更多依賴於語言的評論/文檔特徵,而不是語言的靜態/動態類型本質。更多的是依賴於使用的文檔工具,因爲一種語言通常存在多種不同的文檔工具。儘管在靜態類型語言中,您不必記錄參數的技術類型,但仍需要記錄其含義和用途。

一組具有C派生語法的語言使用Javadoc樣式註釋。例如,在PHP:

/** 
* Calculates the area of circle. 
* @param float $radius The radius of circe. 
* @return float The area 
*/ 
function area($radius) { 

Ruby的院子裏工具使用類似的約定:

# Calculates the area of circle. 
# @param [Number] radius The radius of circe. 
# @return [Number] The area 
def area(radius) 

我想就整體而言,這是最主流風格。

在您需要記錄參數列表時,您可以使用多種語言編寫非常自由的註釋,使用項目符號列表等。這方面的一個有趣的例子是Perl,以它的莢評論:

=item stuff(radius) 

Calculates the area of circle. 

=cut 

sub stuff { 

相反,由RALU提供的例子,我認爲這是比較常見的有函數定義之前的文檔......但最終這一切都取決於在語言上。

1

Python在函數定義後使用註釋,MATLAB在函數定義後使用註釋。

def fibo_gen(): 
    '''Generate Fibonacci numbers; return an iterator''' 
    x, y = 0, 1 
    while True: 
     yield x 
     x, y = y, x + y 

和Matlab

function addtwo(x,y) 
% addtwo(x,y) Adds two numbers, vectors, whatever, and 
%    print the result = x + y 
x+y 

我不熟悉白衣其他動態語言。這被認爲是適當的評論慣例,在這兩個例子中都使用了whit幫助功能。