Utilities in a namespace or in a class?
So far, if I need some commonly used utility functions, I have moved them into the utility class. Thus:
#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 there is another option for that. I could move all my functions to namespaces. Thus:
#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 );
};
To me this seems like a better solution for creating a utility class than a namespace. I see that I need to enter more, but if I need to define a new namespace for all function groups of functions, this will be a little extreme for me. I usually don't create new namespaces other than classes, so 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 better performance for using namespaces for this purpose?
- does he fit better in terms
C++
? - Is there any other reason for using namespaces for this?
I would like to know your opinion, but I need an explanation. I don't want to rewrite my existing codes and write new ones with a different style "just because". I need some kind of language / performance explanation or any other explanation as to why to use it in one way or another.
Thanks for the help.
source to share
I believe that in your case, using a namespace is the best choice for a variety of reasons.
For example:
- It looks like your functions are not exchanging data.
- Namespaces include ADL (Dependent Argument Name Lookup).
See any of several style guides. Here's a clip from Google :
* Member, Static Member, and Global Functions Prefer placing non-member functions in a namespace; ... Instead of creating classes just to group static member functions that don't share static data, use namespaces instead. *
source to share