Classics of not using braces in if-else statement

There’s a snippet of code:

if (event == null)
    if (logger.isWarnEnabled()) logger.warn( "event is null");
else
    fireEvent(event);

This beautifully formatted code does not do what its author wanted it to do: The compiler sees this as

if (event == null)
    if (logger.isWarnEnabled())
        logger.warn( "event is null");
    else
        fireEvent(event);

In this case the event is never fired as long as log level includes warning. Things get worse if log level is above warning: fireEvent(null) is executed, however that’s the situation the author tried to avoid.

This is why Java Coding Style Guidelines requires using braces in all cases:

Note: if statements always use braces {}. Avoid the following error-prone form:

    if (condition) //AVOID! THIS OMITS THE BRACES {}!
        statement;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: