When does the "Do One Thing" paradigm become harmful?
Posted
by
Petr
on Programmers
See other posts from Programmers
or by Petr
Published on 2011-11-23T08:03:04Z
Indexed on
2011/11/23
18:03 UTC
Read the original article
Hit count: 335
For the sake of argument here's a sample function that prints contents of a given file line-by-line.
Version 1:
void printFile(const string & filePath) {
fstream file(filePath, ios::in);
string line;
while (file.good()) {
getline(file, line);
cout << line << endl;
}
}
I know it is recommended that functions do one thing at one level of abstraction. To me, though code above does pretty much one thing and is fairly atomic.
Some books (such as Robert C. Martin's Clean Code) seem to suggest breaking the above code into separate functions.
Version 2:
void printLine(const string & line) {
cout << line << endl;
}
void printLines(fstream & file) {
string line;
while (file.good()) {
getline(file, line);
printLine(line);
}
}
void printFile(const string & filePath) {
fstream file(filePath, ios::in);
printLines(file);
}
I understand what they want to achieve (open file / read lines / print line), but isn't it a bit of overkill?
The original version is simple and in some sense already does one thing - prints a file.
The second version will lead to a large number of really small functions which may be far less legible than the first version.
Wouldn't it be, in this case, better to have the code at one place?
At which point does the "Do One Thing" paradigm become harmful?
© Programmers or respective owner