D - 合同式程式設計



D 程式設計中的合同式程式設計專注於提供一種簡單易懂的錯誤處理方法。D 中的合同式程式設計透過三種類型的程式碼塊實現:

  • 主體塊
  • in 塊
  • out 塊

D 中的主體塊

主體塊包含實際的執行功能程式碼。in 和 out 塊是可選的,而主體塊是必須的。下面顯示了一個簡單的語法。

return_type function_name(function_params) 
in { 
   // in block 
} 

out (result) { 
   // in block 
}
 
body { 
   // actual function block 
}

D 中用於前置條件的 In 塊

in 塊用於簡單的前置條件,驗證輸入引數是否可接受以及是否在程式碼可以處理的範圍內。in 塊的一個好處是,所有入口條件都可以集中在一起,並與函式的實際主體分開。下面顯示了一個驗證密碼最小長度的簡單前置條件。

import std.stdio; 
import std.string;
  
bool isValid(string password) 
in { 
   assert(password.length>=5); 
}
 
body { 
   // other conditions 
   return true; 
}
  
void main() { 
   writeln(isValid("password")); 
}

編譯並執行上述程式碼時,它會讀取上一節中建立的檔案,併產生以下結果:

true 

D 中用於後置條件的 Out 塊

out 塊負責處理函式的返回值。它驗證返回值是否在預期範圍內。下面顯示了一個包含 in 和 out 的簡單示例,它將月份、年份轉換為組合的十進位制年齡形式。

import std.stdio;
import std.string;

double getAge(double months,double years) 
in { 
   assert(months >= 0); 
   assert(months <= 12); 
}
 
out (result) { 
   assert(result>=years); 
} 

body { 
   return years + months/12; 
} 
 
void main () { 
   writeln(getAge(10,12)); 
} 

編譯並執行上述程式碼時,它會讀取上一節中建立的檔案,併產生以下結果:

12.8333
廣告