2011/01/20

Syntax highlighting

In my last post, I included some C++ code snippets. I always wondered how to provide syntax highlighting when posting some code, so a quick Google search for html syntax highlighting headed me towards tohtml.com.

It's a really useful and simple web app for the occasional code blogger, since I was afraid of the possibility that I would have to manually edit the blog's template CSS to achieve it.

2011/01/16

Loops on STL containers

C++ and STL are my everyday working tools. I have get used to use the same construction to iterate through the elements in an STL container:


I've seen most people use a for instead of a while loop:


I find the following reasons to prefer the first over the second option:
  1. The statement for the for loop is too large and usually need to be split into 2 (ugly) or 3 (same as while) lines.
  2. In the while option, operations are performed on the variable Object instead of the iterator itElement, yielding a cleaner and more readable coding style. This becomes a greater advantage when the container is a map instead of a vector.
  3. If some elements must be removed from the container, the for loop is simply not an option, whereas the while option is the way to go.

2011/01/03

C++ exceptions

I've been updating some library code to add new functionality lately. This involved some refactoring and moving classes through namespaces.

So I've been thinking about a clean way to use and manage exceptions. I like the approach of libxml++: it is clean, simple and functional. But I find it hard to emulate this approach when writing my own libraries.

These are my guidelines for code design regarding exception handling:
  1. Define a general exception class deriving from std::exception for the whole library.
  2. Derive a new exception class for each class whose methods may throw exceptions. These are declared and defined in the same header and definition files as the class throwing them.
  3. Derive a new class for each specific error type.
  4. Avoid throwing exceptions defined for member classes: members are implementation details, so are the exceptions they throw.
  5. Avoid adding extra data to exceptions such as stack info, this should be managed by throwing a different type of exceptions.