Hello.
When programming in C++ I often (always) use some method of data encapsulation.
This used to mean defining a class, declaring variables and helper functions private and supplying a public interface of member functions:
class A
{
public:
int PublicFunction() { return _privateVariable; }
private:
int _privateVariable;
};
Any user of this class can create an instance of the class and use its public members.
Should implementation specific details happen to change, the public interface of the class can stay the same. This is all fine.
Howeverm, the more I code, the more I find myself in situations where there only needs to (or only should) ever be one instance of a class.
There are many solutions to this, such as the singleton pattern, classes with static member functions etc.
But somehow these designpatterns have always felt wrong to me. It feels like trying to fit the problem to the solution, where the solution always is some form of a class, be it a singleton or whatever.
namespace // private, not accessable from outside this source file
{
int privateVariable = 54;
int PrivateHelperFunction()
{
// can change this to whatever i want without breaking the public interface
return 123;
}
}
namespace PublicInterface
{
bool PerformSomeAction()
{
// Can access "private" varaibles and functions from here:
return PrivateHelperFunction() == privateVariable;
}
}
- bad (or incorrect) use of namespaces
- cannot seperate implementation over many source code files (would you even want to do this?)
- could it make code less reusable maybe?