Sometimes, construct a object has many option parameter.
The traditional solution is to write a construct using many parameters and set paramter which may be changed most possible at first and set the default values for each parameters.
... {
public:
File(std::string filename_ = "",
bool readOnly_ = false,
bool createIfNotExist = false,
int blockSize_ = 4096
//, ... and others
)
...{
...
}
}
all of this will be OK, if you just create File using the default arguements value.
File myFile("Filename.ext");
but if you just want to changed blockSize, then you have to write:
File myFile("Filename.ext", false, false, 8192);
Then is there a better way to operate such construction, The answer is yes and it called: "Named Parameter Idiom"
see the new File class, first abstract the datas of the construct parameters to a class OpenFile:
class File;
class OpenFile ... {
public:
OpenFile(const std::string& filename);
// sets all the default values for each data member
OpenFile& readonly(); // changes readonly_ to true
OpenFile& readwrite(); // changes readonly_ to false
OpenFile& createIfNotExist();
OpenFile& blockSize(unsigned nbytes);
...
private:
friend class File;
std::string filename_;
bool readonly_; // defaults to false [for example]
bool createIfNotExist_; // defaults to false [for example]
...
unsigned blockSize_; // defaults to 4096 [for example]
...
} ;
inline OpenFile::OpenFile( const std:: string & filename)
: filename_ (filename)
, readonly_ ( false )
, createIfNotExist_ ( false )
, blockSize_ ( 4096u )
... {
} ;
inline OpenFile & OpenFile:: readonly ()
... { readonly_ = true; return *this; }
inline OpenFile & OpenFile::readwrite()
... { readonly_ = false; return *this; }
inline OpenFile & OpenFile::createIfNotExist()
... { createIfNotExist_ = true; return *this; }
inline OpenFile & OpenFile::blockSize(unsigned nbytes)
... { blockSize_ = nbytes; return *this; }
}
And the file class is :
public :
File( const OpenFile & params );
...
};
File::File( const OpenFile & params )
{
...
}
And using File will be simple:
using default parameters value, just:
If you wanted just changing blockSize: