jono
jono

Reputation: 47

global instance of class vs namespace

I've been wondering if there was a clear design pattern when dealing with the following situation:

I have some data that is closely related to each other and I want some functions that modify and give behavior to this data. This seems like the perfect situation to use a class however I only need a single instance of the class.

Would it be better to keep the class and have a global instance or to store the variables in a namespace with the functions?

I'm currently doing the namespace approach when I encounter these situations however I don't like the loss of encapsulation yet I also don't like using global variables. I feel like there should already exist a well thought out solution that I've just never heard of before. Anyone can help on the matter?

class example:

class someclass {
public:
    double somedouble = 0.0;
    int someint = 0;

    void somefunc() {
        // do some stuff with the variables
        somedouble = someint * 2;
        ++someint;
    }
} someinstance;

vs

namespace example:

namespace mynamespace {
    double somedouble = 0.0;
    int someint = 0;

    void somefunc() {
        // do some stuff with the variables
        somedouble = someint * 2;
        ++someint;
    }
} // namespace mynamespace

Upvotes: 1

Views: 104

Answers (2)

user12450543
user12450543

Reputation:

IMHO you're thinking incorrectly two things has nothing to do each other, a class/struct and a name space or scope purposes

class or struct purpose is for encapsulating any functional system in form of structured / organized data
so you can use, manipulate, reuse, and grow it easily well

namespace purpose is to ensure the variable/function names are only used correctly on the targets intended wherever the requiring instances resides and will not otherwise used by other than them

Upvotes: 0

Amit Sharma
Amit Sharma

Reputation: 319

There is a difference between the use cases of class and namespace.

The answer to your question is that you should keep a class and have a global instance.

It can be done using namespace as well but that is not a recommended approach because that’s what we have classes for.

Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your codebase includes multiple libraries.

Using namespaces in such cases (you have mentioned above) is strictly not recommended.

Upvotes: 2

Related Questions