Object-oriented design patterns in the kernel, part 1
Posted Jun 2, 2011 22:42 UTC (Thu) by
cmccabe (subscriber, #60281)
In reply to:
Object-oriented design patterns in the kernel, part 1 by Trelane
Parent article:
Object-oriented design patterns in the kernel, part 1
Golang has the "defer" statement, which sets up some statements which will be executed when the current scope exits. So you might do something like this
> func foo() {
> defer fmt.Println("running cleanup");
> ...
> }
Then the printout will happen when you return from the function, whenever that is.
C, of course, has the single exit point idiom, which is used a lot in the kernel. It looks like this:
> int foo() {
> setup_bar();
> ...
> if (ret)
> goto cleanup;
> ...
> cleanup:
> shutdown_bar();
> return ret;
> }
Java, Python, and Ruby have try...finally { }
I have to be honest; I don't think dumping that pile of macros and templates into your code will make it "suck less." I think you just need to use the mechanisms C++ gives you, namely try and catch, and RAII. It may be an extra line or two, but the programmers trying to read your code after you've moved on will thank you.
Especially when you're debugging something, flow control macros are not your friends. Alexandrescu may be able to figure it out in gdb, but he probably doesn't work with you.
(
Log in to post comments)