In Code Complete, chapter 10, it is advised to group related statements, and the following example is given:
void SummarizeData(...) {
...
GetOldData( oldData, &numOldData );
GetNewData( newData, &numNewData );
totalOldData = Sum( oldData, numOldData );
totalNewData = Sum( newData, numNewData );
PrintOldDataSummary( oldData, totalOldData, numOldData );
PrintNewDataSummary( newData, totalNewData, numNewData );
SaveOldDataSummary( totalOldData, numOldData );
SaveNewDataSummary( totalNewData, numNewData );
...
}
It is stated that such grouping and concurrent processing is bad design, and instead gives something more separated:
void SummarizeData(...) {
GetOldData( oldData, &numOldData );
totalOldData = Sum( oldData, numOldData );
PrintOldDataSummary( oldData, totalOldData, numOldData );
SaveOldDataSummary( totalOldData, numOldData );
...
GetNewData( newData, &numNewData );
totalNewData = Sum( newData, numNewData );
PrintNewDataSummary( newData, totalNewData, numNewData );
SaveNewDataSummary( totalNewData, numNewData );
...
}
I do agree that the second approach is easier to read and to understand, and offers cleaner-looking code, at least from my own perspective. So, my question is, are there any disadvantages with the second approach? For example, one possible issue that I could think of is with temporary connections to databases and such:
void SummarizeData(...) {
...
externalDataStore.open();
externalDataStore.save(oldData, numOldData);
externalDataStore.save(newData, numNewData);
externalDataStore.close();
...
}
This first approach would complete both save operations in one open/close cycle. However, with the second approach...
void SummarizeData(...) {
...
externalDataStore.open();
externalDataStore.save(oldData, numOldData);
externalDataStore.close();
...
externalDataStore.open();
externalDataStore.save(newData, numNewData);
externalDataStore.close();
...
}
You have to open and close the connection for each operation. This seems wasteful, but I have no idea how it affects performance in practice.
Sorry for the unnecessarily long question...