Don't do things globally in C++

zigabrencic

Ziga Brencic

Posted on December 6, 2019

Don't do things globally in C++

Don't expect other developers to have a computer size brain.

To often I come across a codebase where objects magically apeare in the code. Then I would ask the developer that wrote the code where the object is coming from and they would go:

  • Developer: Oh yeah that's a special object we defined globaly.
  • Me: Sigh. 🤦‍♂️

Sure when you writing code you are lazy and global objects my seem like a viable solution, but on the long run they never are. If you use global objects your code most probably won't be thread safe so forget about multithreading. Oh and let's not forget that the code will be painful to read for any future developer.

Code organisation

Alt Text

Organise your program from top to bottom. Code that gets called last should be at the end of the file. There are few advantages of this. Code becomes readable like an article. You don't have to specify class/function definition before their implementation. Or in other words there's no need for forward declarations.

As rule of thumb I try to follow these guidelines:

  • code is split into self contained blocks,
  • every code block can have multiple inputs, but only a signle output,
  • don't use global object's ever,
  • if global variable would be convinient use a class,
  • don't hard code anything.

Hard coding is pain in the ass for mentainence and code reading. If data is needed in multiple places in the code pass it around. One more thought. Don't over use classes. There are a lot of cases where a function with multiple inputs and a single output will do just fine.

Alt Text

Global objects

Don't do it. Maybe you think you are smart enough to keep all the global stuff in your head but once your codebase grows to few thousand lines of code (it does pretty fast ;) ) you'll loose track. Sure there maybe a one percent of cases where global stuff makes sense but unless you're doing the computing on scale of CERN or Google you most probably won't come across them.

Global objects never help with code readability. They just increase number of WTF per minute when another developer reads the code.

Localy/Class global

It's true sometimes its handy to have objects/variables available in multiple functions without the need to pass them around every time. In that case you should write a C++ class. The use private to make sure that variables needed in the class stays "global" only in the class. Other parts of the code shouldn't have access to those variables.

For example let's create a C++ class named MyObject:

class MyObject{
private:
    unsigned int hidden_counter;
    double x;

public:
    void print_next(){ // public function
        ++hidden_counter;
        std::cout << x*hidden_counter << std::endl;
    }

    MyObject(double x){ // object constructor
        this->hidden_counter = 0;
        this->x = x;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now to work with the object you can initialize it with:

MyObject  var(3.5);
Enter fullscreen mode Exit fullscreen mode

To then use the public functions do:

var.print_next(); // prints to screen: 1*x = 3.5;
var.print_next(); // prints to screen: 2*x = 7.0;
Enter fullscreen mode Exit fullscreen mode

Advantage of this approach is that we created an environment where hidden_counter is global in scope of the class but isolated from the rest of the program that shouldn't modify it.

If we now write var.hidden_counter = 3; the C++ compiler will complain that we are trying to modify a private variable of class MyObject.

Defensive programing

Another concept worth mentioning. Idea of defensive programming is that our code also specifies how it shouldn't be used. For example by making hidden_counter private inside class MyObject we made sure that hidden_counter can't be modified outside of the MyObject methods. If we would have made hidden_counter public we woldn't prevent the code user from missing the code of MyObject.

To wrapp up. All the time invested into thinking how code should be structured/implemented is worth way more then you imagine. More readable code will decrease the likelihood of you and other coders pulling out your hair. Though don't get stuck in the code planing ;)

💖 💪 🙅 🚩
zigabrencic
Ziga Brencic

Posted on December 6, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related