When comparing a variable with a constant this trick will guarantee your code will work safely when the variable is null.
Here is the wrong way to compare a variable with a constant
public class Defensive1
{
public static final String EXCHANGE_LSE = "LSE";
public void checkExchange(String exchange)
{
if (exchange.equals(EXCHANGE_LSE))
{
// bad, throws NullPointerException if exchange is null
}
}
}
{
public static final String EXCHANGE_LSE = "LSE";
public void checkExchange(String exchange)
{
if (exchange.equals(EXCHANGE_LSE))
{
// bad, throws NullPointerException if exchange is null
}
}
}
This way is safe but non-optimal as you might forget to add the null test
public class Defensive2
{
public static final String EXCHANGE_LSE = "LSE";
public void checkExchange(String exchange)
{
if (exchange != null && exchange.equals(EXCHANGE_LSE))
{
// better but you might forget the null test
// and this quickly gets messy if you need to add multiple conditions
}
}
}
{
public static final String EXCHANGE_LSE = "LSE";
public void checkExchange(String exchange)
{
if (exchange != null && exchange.equals(EXCHANGE_LSE))
{
// better but you might forget the null test
// and this quickly gets messy if you need to add multiple conditions
}
}
}
Simple and safe way to compare your variable, even when it is null
public class Defensive3
{
public static final String EXCHANGE_LSE = "LSE";
public void checkExchange(String exchange)
{
if (EXCHANGE_LSE.equals(exchange))
{
// the constant is never null so always call the
// equals() method on a constant when your comparison includes one
}
}
}
{
public static final String EXCHANGE_LSE = "LSE";
public void checkExchange(String exchange)
{
if (EXCHANGE_LSE.equals(exchange))
{
// the constant is never null so always call the
// equals() method on a constant when your comparison includes one
}
}
}