Until now if I needed some commonly used utility functions I moved them into a utility class. In a way like this:
#pragma once
class QDate;
class QDateEdit;
class QDialog;
class QWidget;
class GuiUtils final
{
public:
static void moveDialog( QDialog* aDialog, const int aMargin = 4 );
static void setMainWidget( QWidget* aParent, QWidget* aChild, const int aMargin = 0 );
static void setValueBlocked( QDateEdit* aDateEdit, const QDate& aDate );
private:
GuiUtils();
};
class DateUtils final
{
public:
static QDate today();
static QDate yesterday();
static QDate firstDayOfWeek();
static QDate firstDayOfMonth();
static QDate firstDayOfQuarter();
static QDate firstDayOfYear();
static int quarter( const QDate& aDate );
static int quarter( const int aMonth );
private:
DateUtils();
};
But I know that there is an other option for this. I could move all my functions into a namespaces. In a way like this:
#pragma once
class QDate;
class QDateEdit;
class QDialog;
class QWidget;
namespace gui_utils
{
void moveDialog( QDialog* aDialog, const int aMargin = 4 );
void setMainWidget( QWidget* aParent, QWidget* aChild, const int aMargin = 0 );
void setValueBlocked( QDateEdit* aDateEdit, const QDate& aDate );
};
namespace date_utils
{
QDate today();
QDate yesterday();
QDate firstDayOfWeek();
QDate firstDayOfMonth();
QDate firstDayOfQuarter();
QDate firstDayOfYear();
int quarter( const QDate& aDate );
int quarter( const int aMonth );
};
For me it seems a better solution for creating a utility class than a namespace. I see that I need to type more, but if I need to define a new namespace for all utility function group it would look a bit extreme for me. I don't usually create new namespaces but classes every time so that's why I use the first option.
But now I would like to know that:
- is there any advantage of using a namespace for this purpose ?
- does it have a better performane of using namespaces for this purpose ?
- does it better fits in the concepts of
C++
? - is there any other reason for using namespaces for this ?
I would like to know your opinions but I need explanations as well. I don't want to rewrite my existing codes and writing the new ones with a different style "just because". I need some language/performance based or any other kind of explanation why to use it in one or in another way.
Thanks for help.
I believe that in your case, using a namespace is a better choice for a variety of reasons.
For example:
See any of several style guides. Here is a clip from Google's:
*Nonmember, Static Member, and Global Functions Prefer placing nonmember functions in a namespace;... Rather than creating classes only to group static member functions which do not share static data, use namespaces instead. *