Commenting a branching IF-THEN-ELSE.

1

October 19, 2021 by Kenneth Fisher

I’m a big fan of comments (MSSQL, Powershell), so along those lines here’s an interesting way to comment an IF-THEN-ELSE block.

IF SERVERPROPERTY ('ProductMajorVersion') >= 13
	IF SERVERPROPERTY ('productlevel') = 'RTM'
		PRINT 'Patch me!'
	ELSE -- SERVERPROPERTY ('ProductMajorVersion') >= 13 & SERVERPROPERTY ('productlevel') <> 'RTM'
		PRINT 'Ok.'
ELSE -- SERVERPROPERTY ('ProductMajorVersion') < 13
	IF SERVERPROPERTY ('productlevel') = 'RTM'
		PRINT 'Upgrade me!'
	ELSE -- SERVERPROPERTY ('ProductMajorVersion') < 13 & SERVERPROPERTY ('productlevel') <> 'RTM'
		PRINT 'Upgrade me anyway!'

I’ll be honest, it’s not like I do a lot of branching if statements, but it does happen, and when it does, the logic can get rather .. complicated. Particularly if there are more than two branches. Not to mention that there is almost always more than a single short print statement between the IF and the ELSE. Because of that I comment the conditions for the ELSE statement. If it gets really complicated I might even start adding comments to the inner IF statements with the logic from the outer IF statement(s). It’s rare that things are that complicated though. Regardless, this is a great way to help you be certain of your logic. Not to mention the next person who works on this code, particularly if that person is future you.

One thought on “Commenting a branching IF-THEN-ELSE.

  1. I’m a fan of comments too. Others have told me that your code “should” be easy enough to read without them. I find myself using them for CASE statements. If anything, they help you know what you were thinking at the time. Like you, I don’t try and go too deep, but sometimes the real world doesn’t play fair.

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 3,755 other subscribers

Follow me on Twitter

ToadWorld Pro of the Month November 2013
%d bloggers like this: