Best way to use multiple classes with shared instance variables

How is everyone? I’m currently working on a C++ project where a class file has become large and unmanageable. The reason being that many functions depend on shared instance variables. I have resorted to passing the header file along to extend the dominant class.

What would be the best way to implement the single responsibility principle and maintain the shared instance variables between several class files? I understand that Singletons and global variables are generally discouraged for various reasons.

A separate data-structure like a key:value store IMO.

2 Likes

Thanks. Think this is what I was looking for. Seems C++ has map as part of the STL which does the key:value store.

It’s not quite what I thought it was initially but it will still work. I still have to declare map as a global and pass the header to any class that needs it. Still better than what I was doing before though. How would this be different than declaring a bunch of extern variables though?

The structure’s dedicated purpose is to house the variables. Think of it as a silo’ed approach.

Global variables are generally bad practice. To mitigate this one can make them immutable but this is not always preferred if the data is always changing. Further, this makes things messy and increases technical debt.

However, having a dedicated ‘store’ will allow you to maintain tight control over the information through your private access methods and mutations.

1 Like

If you think about it in terms of class structure, you don’t really want a ‘manager’ class for everything because it just gets too complicated.

This comes with the added side effect of additional boilerplate just to pass data around, and a performance decrease of the app.

Depending on what you want to achieve, having a dedicated data store might be the way to go.

2 Likes