SFDC String.isEmpty vs. String.isBlank
阿新 • • 發佈:2021-06-22
SFDC String.isEmpty vs. String.isBlank
目錄前言
專案接近尾聲了,開始編寫測試Class了。開始做測試類了之後發現了很多前期設計的問題,程式碼裡考慮的不全面一下子全都顯現出來了。
老生常談的空NULL
,0
(數字為零),''
(空字串),' '
(只有空格)。
在字串判斷時候,發現String提供了兩個類似的方法:
String.isEmpty(String str)
String.isBlank(String str)
這兩個方法都返回一個Boolean
。
測試
Talk is cheap。show me the code!
寫了點測試的程式碼,測測這倆方法有啥不同。
String strBlank = ''; String strNull = null; String strSpace = ' '; System.debug('isEmpty(strBlank):'+String.isEmpty(strBlank)); System.debug('isEmpty(strNull):'+String.isEmpty(strNull)); System.debug('isEmpty(strSpace):'+String.isEmpty(strSpace)); System.debug('============================================'); System.debug('isBlank(strBlank):'+String.isBlank(strBlank)); System.debug('isBlank(strNull):'+String.isBlank(strNull)); System.debug('isBlank(strSpace):'+String.isBlank(strSpace));
結果如圖:
結論
可以通過Log得出結論
- 兩個方法都對字串為:
NULL
,''
(空字串)都能Check出來 String.isEmpty(strSpace)
:會認為空格
也是字元String.isBlank(String str)
:則更加嚴格一點,空格
不被認為有效字元