2018-06-19

UPDATE: NOW IT HAS!! A reason why Apex doesn't have while-case

更新:在 18" summer release 後,有類似的語法可以使用。
所以這篇基本上也不太需要存在了QQ

關於 「Switch-while Statements」的連結:https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_switch.htm




先說我最近K資料得到的重點:while-case 在視覺上比起大量的 if-else 更容易理解,但是 Apex 因其可能存在的 「未定義行為」故不採用。
Staring with my resent note for certification-preparing: while-case is more visual pleasing then parallel-ed, if-else. But the possible "undefined, unwanted behavior" is probably the reason why Apex doesn't have it.

定義:while-case 語法是類C語言中,用來處理大量、等階(相同時間點) if-else 語法時,運用「案例」的觀念,進而折疊、縮短程式碼並增加可讀性的功能。
Define: While-case is a method with the understanding of "case", for C-Like language to shorten and increase readability in code.

而 Apex 語法最主要的存在的目的是提供  SFDC 上的服務,所以在雲端開發、多租戶的前提下,程式碼的行為、記憶體的邊界,比什麼都重要。
Apex, on the other hand, as the main Language on SFDC, with the purpose of cloud development/compiling/execution and with multitenant awareness, guards closely against runaway code by enforcing limits, which prevent code from monopolizing shared resources.






「沒有任何 while-case 是不能用 if-else 改寫的。」
"There is no while-case code can't be rewrite with if-else."

常見的 Language C 中的 while-case 內的 case 區塊並不是「強分區」(使用大括號將指定程式碼包起),而是用 「break;」來標示區塊的尾端。

這種「用得好上天堂,用不好住套房」的工具,程式的效率正確執行與否完全是依靠工程師的邏輯,所以在求學階段我也算是見過不少各種花式操作,畢竟作業基本上就是炫技的場所。



但「縮短程式碼長度」或「增加可讀性」從不是 Apex 語言最在意的屬性。
"Shortening code and increasing readability were never the priority in Apex."

因為 Apex 是多租戶的語言,所以雖然是「類 Java」,但卻是個相當講求「但求無過」的語言。




以我的理解,要在 Apex 裡看到 while-case 出現,至少需要以下兩點:
1. 強迫 while 中存在 default;
2. 每個 case 都有自己對應的 break,並且 case 無法互相包含。

但是把這兩個條件實現的話,就等於把 while-case 靈活的優點給抹煞掉了。所以比起期待 SFDC 僅僅為了「程式碼的可讀性」就改 compiler (或 parser? 我還沒有K到這部分的相關資料。),研究要如何把大量的 if-else 寫得比較容易閱讀,會來的更為有效率。


p.s. 寫韌體或是組語的工程師(或是被同學風騷的走位帥過的同學們)應該都知道有用兩個變數做 sweap 的方法,但是那除了是炫技的做法之外,也是因為變數的數量有限制。

莫忘 KISS: Keep It Simple and Stupid。

沒有留言:

張貼留言

Check for typo before sending