Often you want to test a series of conditions. I was looking at adding a "select" option to the text processor, and the if-else blocks quickly built up:
if (not ListCount (objectandattlist) = 2) {
return ("{" + ProcessTextSection(section, data) + "}")
}
else {
object = GetObject (StringListItem (objectandattlist, 0))
if (object = null) {
return ("{" + ProcessTextSection(section, data) + "}")
}
else if (not HasInt (object, StringListItem (objectandattlist, 1))) {
return ("{" + ProcessTextSection(section, data) + "}")
}
else {
index = GetInt(object, StringListItem (objectandattlist, 1))
if ((0 > index) or (index >= Listcount (elementslist))) {
return ("{" + ProcessTextSection(section, data) + "}")
}
else {
return (ProcessTextSection(ListItem(elementslist, index), data))
}
}
}
How much better would it be if return stopped execution? A series of steps when you test something at each point, and abort if it fails.
if (not ListCount (objectandattlist) = 2) {
return ("{" + ProcessTextSection(section, data) + "}")
}
object = GetObject (StringListItem (objectandattlist, 0))
if (object = null) {
return ("{" + ProcessTextSection(section, data) + "}")
}
if (not HasInt (object, StringListItem (objectandattlist, 1))) {
return ("{" + ProcessTextSection(section, data) + "}")
}
index = GetInt(object, StringListItem (objectandattlist, 1))
if ((0 > index) or (index >= Listcount (elementslist))) {
return ("{" + ProcessTextSection(section, data) + "}")
}
return (ProcessTextSection(ListItem(elementslist, index), data))
This is not some isolated example. Often I am writing a script for a command, and test a series of conditions to see if the command can be completed (is the object in the right place, etc.). If it fails a test, I just want the script to stop. What I end up with though, is a heavily nested maze of curly braces. Then I remember some other condition I need to test for. I should be able to add an extra few steps, but instead I am figuring out which if else goes with what, and indents blocks even more.
I believe the latter format is far more readable, and far less error prone. Furthermore, it would then be consistent with every other language. What do others think? Does anyone every use return in a way that requires the script to continue to the end?