mardi 21 mars 2017

Simplify checking "null or empty" for multiple variables in IF statement

I have two string variables in validation function which should ensure that variables won't be null or empty at the same time (also the case when one is null and other equals to empty, is not allowed).

Current IF statement is very complex as I have to check:

  1. if both are null
  2. if both are empty (if their lengths are equal to 0)
  3. if string1 is null and string2 is empty
  4. if string1 is empty and string2 is null

It is functional but ugly and not "best practice". How can it be simplified?

if ((string1==null && string2==null) || (string1.length==0 && string2.length==0) || (string1==null && string2.length==0) || (string2==null && string1.length==0))

Aucun commentaire:

Enregistrer un commentaire