Let's say I want to call four functions consecutively, which operate on some object of mine. If any of them fails, I want to return FAILURE
without calling the others, and I want to return SUCCESS
iff all of them completed successfully.
Normally, I would do something like this:
if(function_zero(&myMutableObject) == SUCCESS)
{
return FAILURE;
}
if(function_one(&myMutableObject) == SUCCESS)
{
return FAILURE;
}
if(function_two(&myMutableObject) == SUCCESS)
{
return FAILURE;
}
if(function_three(&myMutableObject) == SUCCESS)
{
return FAILURE;
}
return SUCCESS;
Or, if I needed to do some cleanup:
if(function_zero(&myMutableObject) == SUCCESS)
{
status = FAILURE;
goto cleanup;
}
if(function_one(&myMutableObject) == SUCCESS)
{
status = FAILURE;
goto cleanup;
}
if(function_two(&myMutableObject) == SUCCESS)
{
status = FAILURE;
goto cleanup;
}
if(function_three(&myMutableObject) == SUCCESS)
{
status = FAILURE;
goto cleanup;
}
cleanup:
// necessary cleanup here
return status;
However, the project I am working on has some restrictions:
- No
goto
, ever - No early return (one return per function)
- Line length limit
- (EDIT) No exceptions.
- (EDIT) No templates.
This leads me to something like this:
if(function_zero(&myMutableObject) == SUCCESS)
{
if(function_one(&myMutableObject) == SUCCESS)
{
if(function_two(&myMutableObject) == SUCCESS)
{
status = function_three(&myMutableObject);
}
else
{
status = FAILURE;
}
}
else
{
status = FAILURE;
}
}
else
{
status = FAILURE;
}
return status;
Unfortunately, this pushes me up against the line length limit often.
My question to you is: Is there a simpler way of writing this?
Notes & Restrictions:
- I must implement this logic within the code block implied here. I cannot create new functions, refactor or change the overall architecture.
- (EDIT) In reality the functions have very different signatures.