Defining One Entry Point to Write a Variable

I’ve found myself in situations when I spent lots of time debugging because of some variables declared in a base class were written in tens or maybe hundreds of places in the whole hierarchy, across one or multiple projects even. How could you find the right place where the value of such a variable changes? Well, not easy unless you make some changes to the code. In this article I’m going to show how to create a small wrapper to help you there.

But first, some rules of thumb:

  • Don’t make your variables public. This is pretty basic, but I’ve seen experienced people ignoring it; breaking it is a certain cause for maintenance problems.
  • When you have member variables in a base class that can potentially be assigned in many places across the hierarchy make it private, not protected, and provide Get/Set accessors to read and write it. Moreover, prefer to use this accessors in the base class too, instead of accessing it directly. This way you get only one entry point for reading/writing it, so spotting the places where the value changes will be trivial.

If you decide to go with the second rule that I mentioned I can bet you might be tempted to avoid the last advice and write it directly in the base class. Or if you won’t, one of your teammates will. To enforce that, you can use a wrapper class like the one show below.

This template class has the following characteristics:

  • provides a default constructor and an explicit constructor
  • the assignment operator is made private and not implemented, which means you cannot use an object of this type on the left side of an assignment
  • provides the operator T() which allows to read the value without needing an explicit Get accessor
  • provides a Set accessor for changing the wrapper value; this is the only possible entry point for writing
  • has some comparison operators

If you use this to wrap variables in a base class you don’t make it private, but protected in the base class, otherwise you’ll have to provide get/set accessors for the ExplicitWriteVariable object itself. The lacking of operator= will force you though to use the Set() method explicitly.

Here are some samples for using the class:

The following produces an error:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.