Readability with Scopes

by Veli Tasalı   ·   March 23, 2019

experiment architecture scopes

A scope is a context inheriting from the top.

A scope is a context inheriting from the top.

Scoping is a code block similar to if and while but without a keyword. It is useful for many reasons. Readability can be improved by grouping the related code. You can ensure that the code you write doesn't use an unintentional data point or you can use it to free the memory earlier.

try {
  {
    auto * activeConnection = client->communicate(device, connection);
    //todo: other tasks
    delete activeConnection;
  }

  {
    auto * activeConnection = client->communicate(device, connection2);
    //todo: other tasks
    delete activeConnection;
  }
} catch(...) {
  //todo: catch errors
}

There are two different pointers with the name activeConnection in the example above, and they are not in conflict because they are in a different scope.

#include <iostream>

class TmpObject {
public:
  ~TmpObject() {
    std::cout << "TmpObject deleted" << std::endl;
  }
}

int main(int argc, char *argv[]) {
  {
    TmpObject();  
  }

  std::cout << "Main scope" << std::endl;
  return 0;
}

When this C++ code is run, the output is:

TmpObject deleted
Main scope

If we didn't call TmpObject() in those headless braces, the first output was going be Main scope and then TmpObject deleted, however, in the example above, we get rid of TmpObject earlier.

See SeamlessClient and SeamlessServer files for a real-world example.