Is goto to improve DRY-ness OK?
Posted
by
Marco Scannadinari
on Programmers
See other posts from Programmers
or by Marco Scannadinari
Published on 2014-08-17T19:38:43Z
Indexed on
2014/08/18
22:31 UTC
Read the original article
Hit count: 282
My code has many checks to detect errors in various cases (many conditions would result in the same error), inside a function returning an error struct. Instead of looking like this:
err_struct myfunc(...) {
err_struct error = { .error = false };
...
if(something) {
error.error = true;
error.description = "invalid input";
return error;
}
...
case 1024:
error.error = true;
error.description = "invalid input"; // same error, but different detection scenario
return error;
break; // don't comment on this break please (EDIT: pun unintended)
...
Is use of goto
in the following context considered better than the previous example?
err_struct myfunc(...) {
err_struct error = { .error = false };
...
if(something) goto invalid_input;
...
case 1024:
goto invalid_input;
break;
return error;
invalid_input:
error.error = true;
error.description = "invalid input";
return error;
© Programmers or respective owner