溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C++怎么實現一個函數只執行單一邏輯操作

發布時間:2021-11-26 14:22:57 來源:億速云 閱讀:182 作者:iii 欄目:大數據

這篇文章主要講解了“C++怎么實現一個函數只執行單一邏輯操作”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“C++怎么實現一個函數只執行單一邏輯操作”吧!

F.2: A function should perform a single logical operation(一個函數只執行單一邏輯操作)

Reason(原因)

A function that performs a single operation is simpler to understand, test, and reuse.

執行單一操作的函數更容易理解,測試和復用。

Example(示例)

Consider(考慮下面的函數):

void read_and_print()    // bad{    int x;    cin >> x;    // check for errors    cout << x << "\n";}

這是一個綁定到特定輸入的代碼塊,永遠不會找到另一個(不同的)用途。我們可以將函數拆分成合適的邏輯塊并參數化:

int read(istream& is)    // better{    int x;    is >> x;    // check for errors    return x;}
void print(ostream& os, int x){    os << x << "\n";}

這些函數可以在需要的時候組合使用:

void read_and_print(){    auto x = read(cin);    print(cout, x);}

如果有需要,我們可以針對數據類型,輸入/輸出機制,錯誤處理等模板化read()和print(),例如:

auto read = [](auto& input, auto& value)    // better{    input >> value;    // check for errors};
auto print(auto& output, const auto& value){    output << value << "\n";}
Enforcement(實施建議)
  • Consider functions with more than one "out" parameter suspicious. Use return values instead, including tuple for multiple return values.

    懷疑具有多個輸出參數的函數。改用返回值,如果多個返回值時可以使用tuple。

  • Consider "large" functions that don't fit on one editor screen suspicious. Consider factoring such a function into smaller well-named suboperations.

    懷疑超過一個編輯屏幕的巨大函數??紤]將這個函數重構為稍小的經過良好命名的子操作。

  • Consider functions with 7 or more parameters suspicious.

    懷疑包含7個(或以上)參數的函數。

感謝各位的閱讀,以上就是“C++怎么實現一個函數只執行單一邏輯操作”的內容了,經過本文的學習后,相信大家對C++怎么實現一個函數只執行單一邏輯操作這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

c++
AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女