A well-designed program fulfills its intended requirements without surprising users or maintainers. Poor design can produce incorrect results even when the code appears simple. section 1.4.4
The surprising Date class
A Date object created with 2023, 9, 2 is expected to print SEP 2, 2023, but its month lookup uses the supplied number directly. The example makes an incorrect result visible and motivates safer design. section 1.4.4
Design improves through repeated, deliberate changes:
- Iterate through designing, coding, and testing rather than attempting a perfect first implementation. section 2.1
- Backtrack from dead ends or bad design decisions, especially when requirements change. section 2.1
- Reduce change leaks and complexity with cohesion, encapsulation, delegation, loose coupling, extension points, polymorphism, and nonduplicated code. section 2.4
Listing 1.5 (Program 1.4 Surprise): Date.h (poorly designed)
#include <string>
using namespace std;
class Date
{
public:
Date(int y, int m, int d) : year(y), month(m), day(d) {}
string date_string() const
{
return MONTH_NAMES[month] + " " + to_string(day)
+ ", " + to_string(year);
}
private:
const string MONTH_NAMES[12] =
{
"JAN", "FEB", "MAR", "APR", "MAY", "JUN",
"JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
};
int year, month, day;
};
Inspect the compact Date implementation that demonstrates how a small design decision can create a surprising result. section 1.4.4
