Best Practices

Best Practices For If Conditions

In order to make your code more review-friendly it's important to follow the following best practices in handling if conditions.

Be Positive

Always try to be more positive when writing if conditions.

Good

if ( loggedin )
{
}

Bad

// Check the user account is deactivated
if ( ! isNotLoggedin )
{
}

Keep Simple

In order to follow the principle Keep it Simple, try to use bool variables when possible to specify the intentions of the condition. It's also good to use ternary operator when possible.

Good

bool isLoggedIn = (user.time <= TIMEOUT);

Bad

// Check the user account is deactivated
bool isLoggedIn = false;
if ( user.time <= TIMEOUT )
{
	isLoggedIn = true;
}
else
{
	isLoggedIn = false
}

Avoid Magic Numbers

Avoid Magic number by using enums, macros, constants etc. Magic numbers only adds confusion and make code hard to read and maintain.

Good

if ( user.Status == Status.deactivate )
{
}

Bad

// Check the user account is deactivated
if ( user.Status == 2 )
{
}

Protect with Braces

With my years of experience, I've noticed countless times how developers mess up code logic because of not clearly defining the scope of conditionals. To add code clarity, and avoid developer bugs, always surround the statements within if conditions with braces.

Good

if ( user.Status == Status.deactivate )
{
	return true;
}

Bad

if ( user.Status == Status.deactivate )
	return true;

Variables on the Right

Always keep the variable part on right hand side and constant/value part on left hand side while comparison. In the bad example below, the developer intention is to check that the current day is Sunday. However "=" is used instead of "==". This is considered as assignment and some compilers wouldn't even warn the developer about it. In the good example below, compilers will provide compilation errors.

Good

if ( SUNDAY = day )

Bad

if ( day = SUNDAY )

Summary

Writing conditionals in a standard way will only make your code more readable and easier to maintain. It is important that you remain positive when doing conditions, keep it simple, avoid magic numbers, protect with braces, and keeping variables on the right. Please provide your thoughts in the comment section below and we'll try to incorporate them into the posts.

Author image

About Rawad Hilal

Lead programmer with a track record of incorporating user and business requirements into cost-effective, secure and user-friendly solutions known for scalability and durability.
  • Orange County, California, USA