您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關C++中怎么保持函數簡短,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
Large functions are hard to read, more likely to contain complex code, and more likely to have variables in larger than minimal scopes. Functions with complex control structures are more likely to be long and more likely to hide logical errors
大的函數難于理解,更有可能包含復雜代碼,還有可能包含超過最小作用域的變量。包含復雜控制結構的代碼更有可能是長代碼而且更容易隱藏邏輯錯誤。
Consider(考慮如下代碼):
double simple_func(double val, int flag1, int flag2) // simple_func: takes a value and calculates the expected ASIC output, // given the two mode flags.{ double intermediate; if (flag1 > 0) { intermediate = func1(val); if (flag2 % 2) intermediate = sqrt(intermediate); } else if (flag1 == -1) { intermediate = func1(-val); if (flag2 % 2) intermediate = sqrt(-intermediate); flag1 = -flag1; } if (abs(flag2) > 10) { intermediate = func2(intermediate); } switch (flag2 / 10) { case 1: if (flag1 == -1) return finalize(intermediate, 1.171); break; case 2: return finalize(intermediate, 13.1); default: break; } return finalize(intermediate, 0.);}
This is too complex. How would you know if all possible alternatives have been correctly handled? Yes, it breaks other rules also.
We can refactor:
代碼過于復雜。你怎么知道是否所有可能的分支都已經被正確處理了?是的,它也違反了其他的規則。
我們可以重構這段代碼:
double func1_muon(double val, int flag){ // ???}double func1_tau(double val, int flag1, int flag2){ // ???}double simple_func(double val, int flag1, int flag2) // simple_func: takes a value and calculates the expected ASIC output, // given the two mode flags.{ if (flag1 > 0) return func1_muon(val, flag2); if (flag1 == -1) // handled by func1_tau: flag1 = -flag1; return func1_tau(-val, flag1, flag2); return 0.;}
"It doesn't fit on a screen" is often a good practical definition of "far too large." One-to-five-line functions should be considered normal.
“一屏顯示不下”通常是一個定義“過大”代碼的良好實踐。一到五行的代碼應該被認為是正常的。
Break large functions up into smaller cohesive and named functions. Small simple functions are easily inlined where the cost of a function call is significant.
將大函數差分為較小的內聚函數并命名。當函數調用代價過大時簡短的函數容易linline化。
譯者注:不需要過于擔心因為函數簡短而增加的調用代價。
Flag functions that do not "fit on a screen." How big is a screen? Try 60 lines by 140 characters; that's roughly the maximum that's comfortable for a book page.
標記“一屏裝不下”的函數。一屏是多大?試試60行80列。這大概是令人舒適的一頁書的最大值。
Flag functions that are too complex. How complex is too complex? You could use cyclomatic complexity. Try "more than 10 logical path through." Count a simple switch as one path.
關于C++中怎么保持函數簡短就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。