我正在实现一个类来表示遗留文件。这些文件是二进制的,需要进行大量的解析。可能会有数千行代码来解析该文件。我的类中有两个构造函数:
class CrmxFile {
public:
CrmxFile(std::wstring filename);
CrmxFile(std::ifstream& file);
...
}
Run Code Online (Sandbox Code Playgroud)
由于没有文件内容,对象就没有意义,因此所有解析都需要在构造对象时完成。我打算实现一个大型构造函数(带有流参数的构造函数),但我的一位同事认为拥有非常大的构造函数不是一个好的做法。相反,我应该创建一个私有方法来进行解析,并在检查流可读之后从构造函数调用此方法,并且也许读取文件头以验证流包含正确的数据。
是否有任何准则/规则/惯例/等?管理这种情况的?本质上(用伪代码),两种方法中哪一种更好,
长构造函数:
CrmxFile::CrmxFile(std::ifstream& file) {
if (file is not readable) {
throw new CmrxException(read_error);
}
CmrxHeader header(file);
if(!header.isValid()) {
throw new CmrxException(invalid_file);
}
//now do all the reading/parsing of the file
//constructor may end up being a thousand lines of code
...
}
Run Code Online (Sandbox Code Playgroud)
或简短的构造函数和辅助方法:
class CrmxFile {
public:
CrmxFile(std::wstring filename);
CrmxFile(std::ifstream& file);
private:
ParseFile(std::ifstream& file);
...
}
CrmxFile::CrmxFile(std::ifstream& file) {
if (file is not readable) {
throw new CrmxException(read_error);
}
CrmxHeader header(file);
if(!header.isValid()) {
throw new CrmxException(invalid_file);
}
ParseFile(file);
}
void CrmxFile::ParseFile(std::ifstream& file) {
//do all the reading/parsing of the file here
...
}
Run Code Online (Sandbox Code Playgroud)
助手在这里似乎可行..
但是,我不会将其设为私有:而是将其拆分为多个尽可能小的函数,驻留在详细信息或解析器命名空间中,以便您可以测试每个方法。因为无论如何你都使用流,所以这很简单:更改你的方法以接受 anistream而不是ifstream,然后测试的输入可以是纯字符串,然后将其输入到用作方法参数的 istringstream 中。相信我,您会想测试一下,正如您现在所说,它将有数百行,您不可能从第一次就得到正确的结果。
实际的辅助方法不是简单地组合较小的方法,或者根据您拥有的数量,组合较小的方法,进而组合其他方法。