I am working with a pre-written function that currently contains multiple return statements throughout it. Since I was told in school that every function should have one and only one return statement, I was wondering if there is any construct in DXL like a goto statement which could allow a program to skip over the remainder of a function and go to the end of the function. I've seen the continue and break statements, but those are only good if you're in a loop. In this function, there are a number of error checks throughout which return a string value. I'd like to change it to set a string variable then skip to the end where I would have the return-statement return the string variable. In general, if possible, I'd like to have something that works a bit like the following quasi-code:
string someFunction() {
string errMsg = "";
...
... //run some code
...
if (errCondition1) {
errMsg = "Error message 1";
goto exitFunc;
}
...
... //run more code
...
if (errCondition2) {
errMsg = "Error message 2";
goto exitFunc;
}
...
... //run more code
...
exitFunc:
return errMsg;
}
Chris chrscote - Tue Jan 03 09:08:02 EST 2017 |
Re: Change multiple returns to one you should of also learned not to use "goto" statements along with multiple 'return" statements in school depending on the language. DOORS doesn't have a goto/switch statement using if/ifelse/else conditions if you want to limit multiple return statements.
string someFunction() {
string errMsg = "";
...
... //run some code
...
if (errCondition1) {
errMsg = "Error message 1";
} else {
...
... //run more code
...
if (errCondition2) {
errMsg = "Error message 2";
} else {
...
... //run more code
...
}
}
return errMsg;
}
|
Re: Change multiple returns to one The second very common approach, especially if you want to avoid nesting, is to set a flag:
string someFunction() {
string errMsg = "";
...
bool flag = true;
... //run some code
...
if (errCondition1) {
errMsg = "Error message 1";
flag = false;
}
if (flag) {
...
... //run more code
...
}
if (flag && errCondition2) {
errMsg = "Error message 2";
flag = false;
}
if (flag) {
...
... //run more code
...
}
return errMsg;
}
Just for completeness sake. Regards, Mathias |