El Fuego (phreakhead) wrote,

Trinary Logic: The If...Else...Finally Construct

I've been wanting this in a programming language for a long time: an if...else...finally block. Basically the rule is this: you have a normal if...else block, but you can put a "finally" condition anywhere you want after the first "if". Any "finally" block appearing (there can be more than one) is executed iff one of the conditional branches above it was followed, within the scope of the followed branch. Execution then continues down the chain. This is a useful shortcut when you have very similar code that is executed when a few conditions are met, but not all of them.

Here's a simple example:

if (a) {
	option = a.getOption();
	normalizeOption(option);
	prepareOption(option);
	processOption(option);
	renderOption(option);
}
elseif (b) {
	option = b.getOption();
	prepareOption(option);
	processOption(option);
	renderOption(option);
}
else {
	option = null;
}


could be written as:

if (a) {
	option = a.getOption();
	normalizeOption(option);
}
elseif (b) {
	option = b.getOption();
}
finally {
	prepareOption(option);
	processOption(option);
	renderOption(option);
}
else {
	option = null;
}


This would come in handy so often that I almost want to modify some open-source compiler to recognize these constructs. I've come across better examples but I can't think of them right now. Try coming up with some of your own.
Tags: programming, work
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded  

  • 4 comments