|
|
|
|
|
by kstenerud
5351 days ago
|
|
Good copy/paste: Anything boilerplate such as manually initialized structures/arrays of stuff, language-specific boilerplate (Java comes to mind here) that is essentially the same repeated shit but you gotta do it anyway, unrolling loops, setting up switch statements. Anything unavoidable (or too expensive to refactor) that's repetitive. Preprocessor macros: Code generators, compile-time switchable code (such as logging) without filling your source files with #ifdefs Goto: Managing complex resource allocation/deallocation within a function: bool success = false;
int fd = -1;
char* memory = NULL;
fd = open(filename, "rb");
if(fd == -1)
{
LOG_ERROR("Could not open %s: %s", filename, strerror(errno));
goto done;
}
memory = malloc(BUFF_SIZE);
if(memory == NULL)
{
LOG_ERROR("Out of memory");
goto done;
}
for(blah blah blah)
{
if(failed to read or whatever)
{
LOG_ERROR("It's borked");
goto done;
}
}
...
success = true;
done:
if(memory != NULL)
{
free(memory);
}
if(fd != -1)
{
close(fd);
}
return success;
I disagree that dismissing a tool out of hand as an "abomination" is a commendable approach. If you take that attitude (or instill it in others), you'll probably never learn the proper use of such a specialized tool, leaving you ill-equipped to deal with the situations those tools handle well. |
|
Unrolling loops: I never saw an instance where that was necessary. Plus, the compiler can often do it for you. I know we often use high performance applications (video decoders, 3D games…), but very, very few of us write ones.
Switch statement: the syntax of the construct is heavy, we should lighten it. The rest is hardly boilerplate any more:
Preprocessor macros: I agree (I mean, I back-pedal), they are more useful than the rest. However, I still avoid them by default, as they make really good foot-guns.Goto: your example shows exceptions (try…catch finally here). Goto makes much less sense when you have them.
Now my point isn't to never do those things at all. Only to think of them as last resorts. The "Chtulu Abomination" metaphor helps me do that.