LoginSignup
26
25

More than 5 years have passed since last update.

Apexでのnullとか空チェック

Posted at

普段あまり深く考えず、とりあえずでチェックしているので、少し整理してみました。

以下は単純に== nullでOK

  • ID
  • Integer
  • Decimal
  • Double
  • Date
  • Datetime
  • Time

Stringは空文字列と、空白文字があるので、状況に応じて使い分けます。

以下、挙動の比較

String nullString = null;
String emptyString = '';
String blankString = '    ';

// ==null
System.debug(nullString == null); //true
System.debug(emptyString == null); //false
System.debug(blankString  == null); //false

// == ''
System.debug(nullString == ''); //false
System.debug(emptyString == ''); //true
System.debug(blankString == ''); //false

// String,isEmpty(inputString)
System.debug(String.isEmpty(nullString)); //true
System.debug(String.isEmpty(emptyString)); //true
System.debug(String.isEmpty(blankString)); //false

// String,isNotEmpty(inputString)
System.debug(String.isNotEmpty(nullString)); //false
System.debug(String.isNotEmpty(emptyString)); //false
System.debug(String.isNotEmpty(blankString)); //true

// String,isBlank(inputString)
System.debug(String.isBlank(nullString)); //true
System.debug(String.isBlank(emptyString)); //true
System.debug(String.isBlank(blankString)); //true

// String,isNotBlank(inputString)
System.debug(String.isNotBlank(nullString)); //false
System.debug(String.isNotBlank(emptyString)); //false
System.debug(String.isNotBlank(blankString)); //false

//inputString.isWhitespace()
System.debug(nullString.isWhitespace());//ぬるぽ
System.debug(emptyString.isWhitespace()); //true
System.debug(blankString.isWhitespace()); //true

List, Set, Map

nullチェックは== null
空チェックは.isEmpty()
なので、hoge != null && !hoge.isEmpty()という使い方が多いかな?

なお、 クエリの結果をリストに格納した場合、値がとれなくてもnullにはならないので、nullチェックはしなくて良いみたい。
また、クエリで取得したsObjectの項目の値は、文字列系の項目であっても空にはならないので、nullチェックのみで良さそう。

26
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
25