Lately, I have been playing with this idiom:
Changing a private member variable into a local static variable when:
- member to singleton class used in only one function
- member is mutex for a shared resource used in only one function.
- member is constant expression used in only one function.
Looking through my code, I picked up 3 instances where I did this:
/* On Singleton Classes */
void MainWindow::on_lineEdit_Filter_textChanged( const QString &text )
{
static QString s;
if ( text == s ) { return; }
s = text;
this->filter(text);
}
/* On Mutexes */
void PdfScraper::onFindKeywordFrequency( Tag t, QString designation, int n )
{
static QMutex m;
m.lock();
db_Pdf.setValue( t, designation, n ); // db = database
m.unlock();
}
/* On Constants applicable to one function */
void QPixmapCrop::evaluateImage()
{
QString pictureText = MainWindow::getPictureText( f_TempCrop.fileName() );
s_SaveEvent->setTitle( QPixmapCrop::findTitle( pictureText ) );
s_SaveEvent->setDate ( QPixmapCrop::findDate ( pictureText ) );
s_SaveEvent->setTime ( QPixmapCrop::findTime ( pictureText ) );
s_SaveEvent->setTheme( QPixmapCrop::findType ( pictureText ) );
s_SaveEvent->setTags ( MainWindow::getTagList( pictureText ) );
/* Find Weekly Day */
{
const static QRegularExpression re( R"((?is)^.*(sundays|mondays|tuesdays|wednesdays|thursdays|fridays|saturdays).*$)" );
if ( pictureText.contains(re) ) {
QString s = QString( pictureText ).replace(re, "\\1");
const static QRegularExpression re_1( R"((?is)^sundays$)" );
const static QRegularExpression re_2( R"((?is)^mondays$)" );
const static QRegularExpression re_3( R"((?is)^tuesdays$)" );
const static QRegularExpression re_4( R"((?is)^wednesdays$)" );
const static QRegularExpression re_5( R"((?is)^thursdays$)" );
const static QRegularExpression re_6( R"((?is)^fridays$)" );
const static QRegularExpression re_7( R"((?is)^saturdays$)" );
s.replace(re_1, "Sundays" );
s.replace(re_2, "Mondays" );
s.replace(re_3, "Tuesdays" );
s.replace(re_4, "Wednesdays");
s.replace(re_5, "Thursdays" );
s.replace(re_6, "Fridays" );
s.replace(re_7, "Saturdays" );
s_SaveEvent->setDay(s);
}
}
/* ... etc ... */
Given all this, are my principles thus far, sound? Are there any more that can be added?
I would also like to touch upon:
- Interpretation: how does one typically interpret local static variables when coming across them in the wild?
- Performance & Memory Footprint: can or will this make a difference at all?
- Readability: when does it help or hinder the readability of code?