To static or not to static?
-
@mranger90
FWIW, personally I find that an extraordinarily burdensome guideline. Small utility methods which happen not to usethis
but are useful privately in a class (and perhaps meaningless elsewhere) are not at all uncommon. (I haven't done so, but I would be surprised if I don't find such in, say, Qt sources.) Having to move them out does not seem nice to me. But what do I know, I respect you say that is what your company requires.EDIT
I don't have downloaded Qt sources. Just using woboq for Qt5 and having a look at, say,QString
forprivate static
methods I happenstanced on, say, declaration https://codebrowser.dev/qt5/qtbase/src/corelib/text/qstring.h.html#_ZN7QString14compare_helperEPK5QChariS2_iN2Qt15CaseSensitivityEprivate: static int compare_helper(const QChar *data1, int length1, const QChar *data2, int length2, Qt::CaseSensitivity cs = Qt::CaseSensitive) noexcept;
/*! \internal \since 4.5 */ int QString::compare_helper(const QChar *data1, int length1, const QChar *data2, int length2, Qt::CaseSensitivity cs) noexcept { Q_ASSERT(length1 >= 0); Q_ASSERT(length2 >= 0); Q_ASSERT(data1 || length1 == 0); Q_ASSERT(data2 || length2 == 0); return qt_compare_strings(QStringView(data1, length1), QStringView(data2, length2), cs); }
A perfect example of a private utility method that they seem to declare
static
as I would have done (though I have not checked whether it might be called from somestatic
method). -
@JonB said in To static or not to static?:
compare_helper
qt_compare_strings is static as well. That may be the reason why compare_helper is static. It does have to be, I guess. If not, the return is different.
return QString::qt_compare_strings(QStringView(data1, length1), QStringView(data2, length2), cs);If the static function performs operations that are related to the class as a whole, rather than specific instances, it may make sense to keep it static and private.
I do not know if it is a good practice or not. all math funcs for exampes std::cos are defined in namingspace std. The reason could be that template for class member funcs were introduced in C++ 14. In or before C++ 11, it was not possible to use template for member funcs in a class.
-
@JoeCFD said in To static or not to static?:
qt_compare_strings is static as well. That may be the reason why compare_helper is static
Sorry, that does not make sense. You can of course call a
static
function from a non-static member function, just not the other way round. This would not be any reason to choose to make the calling method,QString::compare_helper()
, bestatic
.it may make sense to keep it static and private
But you can see the other responders here are suggesting I do not make
private
methodsstatic
, which I am now following. -