[SalesForce] unexpected syntax: ‘missing SEMICOLON at ‘if”

I am trying to debug this error.

unexpected syntax: 'missing SEMICOLON at 'if''

public Boolean validateName(String name){
    return if ( name == null || name =='' || name.length() < 3) ? true : false;           
}

Any idea what I am missing?

Best Answer

Ternary operators don't need if defined. So your return statement should just read:

return (name == null || name =='' || name.length() < 3) ? true : false;

Or, as @AdrianLarson pointed out in the comments you could just use:

return (name == null || name =='' || name.length() < 3);

Which saves a few bytes of code whilst still delivering the same result.

Edit

There's a few ways to achieve what you want here, based off of the comments on this post. For instance, from IllusiveBrian:

return String.isEmpty(name);

This returns a boolean value depending on whether or not the String is empty. Pretty self explanitory!

Additionally, Sebastian Kessel mentions you can use:

return String.isBlank(name);

Would also return a boolean value whether or not the String is empty.

The difference between these functions are as follows:

isBlank(inputString)

Returns true if the specified String is white space, empty (''), or null; otherwise, returns false.

isEmpty(inputString)

Returns true if the specified String is empty ('') or null; otherwise, returns false.

These are from the docs.

The long story short is that there's a number of ways to handle your specific use case. You can use many functions that will return either true or false.

But, with respect to ternary operators, you just didn't need the if part meaning if you, for instance, wanted a ternary operator that returned a String, you'd do so as follows:

public static String HelloWorld(Boolean x) {
  return (x) ? 'Hello' : 'World';
}