Exceptionless Programming

| Comments

I am a big fan of writing code that generates no runtime errors. This is an implementation of a function that takes the first element of an array.

1
2
3
4
5
6
template<typename T>
T first(std::vector<T> array)
{
  if (array.size() == 0) { throw EmptyArrayException(); }
  return array[0];
}

This is the standard way we are taught to write programs. However, there is another way to write this function that makes the exception unneccessary.

1
2
3
4
5
6
7
8
9
template<typename T>
void first(std::vector<T> array, std::function<void(T)> returnCallback)
{
  if (array.size() == 0)
  {
      return;
  }
  returnCallback(array[0]);
}

Suddenly the program flow is dictated by the emptiness of the array. Besides knowing well that this function will never throw an exception, the program that uses it will be structured in such a way that you can guarantee within the scope of the returnCallback function that was passed in, the function will always have the first element of the array. You don’t even have to check for nullness.

1
2
3
4
5
6
7
8
9
10
11
12
13
int calcCheckSum(std::vector<int> sorted)
{
  int result = 0;
  first<int>(sorted, [&amp;](int a)
  {
      int& res = result;
      last<int>(sorted, [&amp;](int b)
      {
          res = a + b;
      });
  });
  return result;
}

And as a perk, if this function compiles, you know that it will run without errors.

Comments