Blog Post

Commenting a branching IF-THEN-ELSE.

,

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.

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

Share

Share

Rate