← Back to team overview

kicad-developers team mailing list archive

What is a global variable, and why we don't need them.

 

My definition:

I like to abstract the definition a little more than some designers, and include things
like singletons because a singleton intends to limit the number of instances to one.  I
would think you still have a global variable if you wrapped it into a class with a single
static instance.  You still only have one global instance.  That to me is still a global
variable with a fancy accessor, and that might even be worse.

If you can instantiate multiple instances, and the pointers to those instances are in
client user objects or on the stack, then you are probably not using a global.

Think of the world as being the *one* globe that we live on.  We have a global air supply,
and it spans all countries.  It is global because we cannot instantiate another instance
of the world's air supply, not because of how we spell its name, or where it exits.


The purpose of the PROJECT class was to create a place to store project specific objects,
with full intention of supporting more than one open project at some point in time.  You
can see this vision laid out in kiway.h.  Not a KiCad day goes by when I don't have
multiple KiCad projects open at the same time.  Currently, I typically am working on one
project under the project manager, but then load eeschema or pcbnew in singletop mode to
"view only" the other project data.

And even if multiple projects is not currently on the todo list, I think it is a mistake
to put road blocks in the path of supporting multiple projects at the same time.  It is
trivial to avoid those road blocks in most cases: avoid globals, including singletons
where one instance would not satisfy all projects. Instead, just use PROJECT and stuff
your PROJECT specific stuff into a PROJECT::_ELEM.

I recently got rid of g_RootSheet by using PROJECT.  It evolved through a can of worms,
but the worms are now all dead.  And the result is better than the formerly closed can of
worms.

One of the coolest features of PROJECT is the "data on demand" paradigm, or some might
call it lazy loading.  For python clients and what not, and any type of window client of
the PROJECT, it leaves the loading code out of sight and in a common place.

The main danger is the use of the virtual destructors in PROJECT::_ELEM.  That takes some
getting used to.  You must destroy any PROJECT elements that you own before your DSO gets
kicked out of process. This means as you exit EESCHEMA, that DSO might get unloaded from
ram, particularly if all windows in eeschema are closed.  I don't know that this unloading
happens, but because it could happen, it is best to design for it.  And mostly that means
calling
  SetElem( ELEMTYPE, nullptr );

in your clients' last destructor.






Follow ups