Re: Goto still considered helpful



Peter Pichler <usenet@xxxxxxxxxxxxx> wrote:

[SNIP: Examples]

Which one is more readable?

I actually found your version a little tricky to read. I find
functions more readable if all the clean up happens in one place.

It took me a few seconds to make sure your files were properly closed
no matter what series of events happened.

Using your approach, things would get more tricky pretty quickly if
more resources were added to the function, such as dynamically
allocated read and write buffers.

Also, your approach unnecessarily duplicates code. Even your simple
example contains multiple calls to close the very same file.

I like the following pattern, which keeps the resource clean up in one
place, and the pattern scales well if more resources are added to the
function in the future:

int fcopy(char const *dst, char const *src)
{
FILE *sf = NULL;
FILE *df = NULL;

sf = fopen(src, "r");
if (!sf)
goto done;

df = fopen(dst, "w");
if (!df)
goto done;

/* copy happens here */

done:
if (sf)
fclose(sf);
if (df)
fclose(df);

return /* value indicating success or failure */ 0;
}
.



Relevant Pages

  • Re: Goto still considered helpful
    ... which keeps the resource clean up in one ... and the pattern scales well if more resources are added to the ... int fcopy(char const *dst, char const *src) ... goto done; ...
    (comp.lang.c)
  • Re: Garbage Colletor
    ... Not only is it much less error-prone than people ... the RAII paradigm itself is a cleaner design compared to ... It's extremely easy to handle resources in C++ as you stated but the ... By clean I mean it's ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Scheduling nightmare!
    ... Welcome to this Microsoft Project newsgroup:) ... Yes, Project is tricky! ... I assume you have 28 resources: one for each set of tasks? ... >> Hello Kev, ...
    (microsoft.public.project)
  • Re: Callback Function requery problem in A97
    ... this event is thus to clean ... and un-load all the stuff you did in the initialize event. ... all those resources and memory and reocrdsets you ... That event will fire when you close the form. ...
    (comp.databases.ms-access)
  • Deleted users show in Project Owners drop down
    ... Resources in the the PWA Admin area called "Clean up Project Server ... database". ... currently in a test environment, it needs to become a production environment ...
    (microsoft.public.project.pro_and_server)

Loading