Oh my god

An old good Unix console joke goes like this:

% ar m God
ar: God does not exist

Obviously thats a very old and used joke, nowdays we’re much more advanced than that:

$ ar m God
$ ar: creating God

Advertisements

Design Patterns: C++ Idiom RAII

Ohh design patterns. I love buzzwords. Who doesn’t? To increase my buzzword count I will be writing about a topic most people programming C++ should already know: RAII, resource acquisition is initialization.

Patterns everywhere

Knowing that Gamma et al didn’t list all the known patterns in the universe does come as a surprise to some, not sure why though. The twenty some patterns they write about in their now famous book are (arguably, perhaps) some of the most common design patterns, but the list hardly finishes there.

Some patterns only have meaning in a very specific context; a reactor is a nice pattern for handling asynchronous events yet most applications would never need it. Sometimes “the context” means a specific domain in which the application must work, like a web application, a real time application or a distributed application, sometimes the context is the language itself. RAII falls in this last domain, it only makes sense for C++ applications (actually there are others, but thinking what kind of languages would support this idiom is left as an exercise for the reader).

No, really. What is RAII?

If you made it past that long intro you are probably really interested in knowing what RAII is, and don’t know how to search it in Wikipedia. OK, I’ll explain it the best I can then: RAII means that a resource acquisition is the initialization.

Seriously. That is all the secret there is to RAII. Talking in code:

template
class RAII_Wrapper {
   T *resource;

   public:
      RAII_Wrapper (T *resource)
            : resource(resource)
      {
         resource->open();
      }

      ~RAII_Wrapper ()
      {
         resource->close();
      }
};

An example

Compare that to a visitor pattern. It’s just too simple to be of any use, isn’t it? Well, contrary to what Java fanboys tend to believe you can do lots of nice things without writing a bazillion lines of code.

int foo() {
	Expensive_Resource x;
	x.open();

	try {
		if (not bar()) {
			x.close();
			return -1;
		}
	} catch (...) {
		x.close();
		throw "up";
	}

	int ret;
	try {
		ret = baz();
	}catch(...) {
		// We don't care, we're closing x anyway
	}

	x.close();
	return ret;
}

Wow… a whole lot of code just for calling bar and baz. And as I wrote that without even compiling I’m sure there are too many hidden bugs, lots of code-paths my simple programmer’s mind can’t even begin to imagine which will cause my Expensive_Resource to be leaked!

Let’s rewrite that using RAII:

void foo() {
	Expensive_Resource x;
	RAII_Wrapper release(&x);

	if (not bar()) return -1;
	return baz();
}

A lot nicer, isn’t it? But, what happened to all the try/catch if’s and closes there?

Where’s the magic?

The magic of RAII lies in how C++ handles exceptions. When we have a built object (can an object be in an unbuilt state?) it means it’s constructor has correctly ran. It also means it’s destructor will run when it goes out of scope, doesn’t mater HOW it goes out of scope.

See how brilant that is? Doesn’t matter if a function we’re calling throws, or if we need to return before reaching the end of the function: the destructor will be called and thus our Expensive_Resource will be free!

Why is this C++ specific?

This is an easy one: think how would you implement this in Java: right, you can’t. Not knowing when is your object going to be destroyed means you can’t do anything useful in its destructor, therefore RAII is deeply rooted within the memory management in C++ and it’s pretty much a language specific pattern (or is it?). But, is that so good?

Not everything is so great…

You are probably thinking this is the best discovery since ice cream was invented. Well, not so fast, RAII has it’s detractors too.

The first problem in RAII, it doesn’t have a graceful way of handling resource acquisition failure. If Expensive_Resource is a database, and it’s connection fails, we have a throwing constructor.

Even if throwing constructors are acceptable, throwing destructors may even be a worst idea: throwing while an exception is already active is a cause for concern (tip: it’ll crash your application, doesn’t matter how many try/catch blocks you use, due to stack unwinding issues).

And then, even if we don’t care about throwing destructors you have the issue of a release failure: how do you notify the user that a release failure has occurred? And what do you do, should it happen?

So, RAII is a great idea indeed, and it has it’s uses, but you should be careful when choosing this C++ specific pattern.


Fuuuuuuuuuuuuuu (Opera)

I hate ubuntu, but I hate windows the most. I hate firefox, but internet explorer makes me want to vomit. I don’t like gnome, but kde is uglier. But I love Opera. Well, loved it, I guess version 10.60 will be my last version.

It’s been a loyal application which I’ve been using since its 6.x version. Always fast, with all the functionality I needed (some more too) and none of the bloated BS needed to make FF be a usable (though ugly) browser. It had it’s ussual screw-ups, everyone does, but after I updated to version 10.60 it has become unusable.

Its new features include random crashe, making gmail work really slow (or not at all: the fucking scrollbar won’t work anymore, and keyboard shortcuts in google reader (j & k, next & prev) are foobar’d. Scrolling on a large webpage eats 100% cpu, the upgrade fucked up my nice dark theme (and changed it back to a hellish abomination which seems to be a time-traveller from 1998), and it has random stupid bugs. And I mean STUPID, like, double click a word and the popup menu won’t go away.

I tried to insert this image through WP image uploader, but it doesn’t work anymore in Opera
Fuck. I always liked you Opera, but it seems it may be time to give chrome a chance.


Template metaprogramming XI: Hidden Agenda

Wow, number eleven already. We’re getting more chapters here than Final Fantasy games. I didn’t even imagine there was so much to write about such an esoteric language features like templates. I do wonder if anyone will actually read it, but that’s a completely different problem.

malboro

Enough meta-meta talk: what can we do with all the things we have learned? We can calculate pi and e, we already showed that as an example on one of the first chapters. This chapter I’m going to write about what motivated me to explore the bizarre underworld of template metaprogramming. Some time ago I had to work with a Berkeley DB researching the feasibility of developing a magic cache for (real) DB table. Leaving aside the discussion of whether this is a good idea (the project did have a good reason to be researched) I hit a major roadblock when trying to provide a fa├žade for every table; something like this:

virtualtemplate

See the problem? To do something like that we’d need a virtual template method, and you can’t have that. After seeing that I thought to myself “Hey, I’ll use templates!”. Then I had two problems, but the damage was done, I couldn’t go back. What kind of contorted device could we implement to make such a devious requirement work? I’ll leave you to think it, the answers I came up with next week.


Thanks for flying vim

Have you ever used Vim through ssh and saw your xterm title changes to “Thanks for flying vim”? It happens a lot to me, and I usualy notice about an hour later. I’m not sure what’s the use of this, I guess it’s related to Vim airlines (no, really, check vim-avia.com), but it can be turned off:

When using vim in an xterm it renames the title of that window to “Thanks for flying vim” on exit.

Q: How to turn off the message “Thanks for flying vim”?
A: :set notitle

http://www.vmunix.com/vim/answ.html


The truth about SNMP

Seen @ http://wiki.wireshark.org/SNMP:

After years thinking and reading RFCs and various other documents, today, I finally understood. “Simple” refers to “Network” not to “Management Protocol”! So it is a Management Protocol for Simple Networks not a Simple Protocol for Management of Networks… That explains why it’s called “Simple”. It was that Simple but it took me years to understand it! — LuisOntanon

Thank you Luis. That explains a lot.


Opera borks gmail

Ubuntu sucks, but less than windows. Gmail sucks, but less than hotmail. Opera rocks, but it tends to fuck up gmail every once in a while. After a lot of research and having found no help on the interweb I traced the problem to having a lot of tabs open for a lot of time (weeks, not hours).

In Firefox this shouldn’t be a problem as having a FF browser open for a week should hog all the memory on its host computer, forcing you to reboot. In Opera, being a little bit better behaved browser, this may actually be a problem.

Luckly the fix is simple: open a Vim editor or take out pencil and paper, make a list of all your open tabs, close opera and using your favourite console type “rm -rf ~/.opera/sessions” (i.e. delete the sessions folder in your .opera dir). Restart Opera and restore your tabs from your backup list. Problem should be gone.


Elvis is alive!

Unix trivia day: in the olden days of the 90’s there were a lot of Unix boxes out there named “elvis”. Nowdays it’s not uncommon to find one, either. Have you ever wondered why are there so many boxes called elvis?

This is related to Solaris’ ping command. When you ping $HOST it prints “$HOST is alive” (if it’s responding the pings), thus elvis is alive!