HRESULT MyFunction()
{
//init
char * string = new char[20];
//call a function. clean and return error code if failure
if (FAILED(SomeFunction(string)))
{
delete string;
return (ERROR_CODE);
}
//call another function. clean and return error code if failure
if (FAILED(SomeOtherFunction(string)))
{
delete string;
return (ERROR_CODE);
}
//and so on with more functions..
//clean and return some success code
delete string;
return (SUCCESS_CODE);
}
Now, as you can see, the code gets ugly because of all the cleaning inside every if-failed-statement. When I have even more cleaning stuff to do, like 5 lines or something, this layout forces me to write lots of extra code and it looks ugly. So, as I said before, I know several ways to improve the code and here they are:
1. Create a function called MyFunctionCleanup which performs all the cleaning and call it right before every return. In the above exemple this would require just as much code in the primary function but when the cleanup consists of more code this helps a bit.
2. Using goto. This solution looks great, but everyone tells you not to use goto and I personally never do. Should I?
3. Doing something like the following:
HRESULT MyFunctionCore(char * string)
{
if (FAILED(SomeFunction(string)))
return (ERROR_CODE);
if (FAILED(SomeOtherFunction(string)))
return (ERROR_CODE);
return (SUCCESS_CODE);
}
HRESULT MyFunction()
{
//Init
char * string = new char[20];
//Main function call
bool resultat = MyFunctionCore(string));
//Cleanup
delete string;
return (resultat);
}
If you gotten this far, thanks for taking some of your valuable time and trying help me. Im not necessarily looking for the perfect, supergeneric, extravagant solution when posting here, but rather some opinions on which of my three ways you would choose (and why) or some new thoughts or methods of doing it. I simple want to know what you think and/or how you deal with situations like this one.
Thanks!