HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppModerate

Is this Date class well-written?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thiswrittendatewellclass

Problem

I'm a C++ beginner and have made a simple class. But I'm not sure if this is well-written. It's basically just a Date class.

#include 

using namespace std;

class Date{
    int d, m, y;    //Day, Month, Year
public:
    Date(int dd = 1, int mm = 1, int yy = 1);

    int addDay(const int &dd) { d += dd; }
    int addMonth(const int &mm) { m += mm; }
    int addYear(const int &yy) { y += yy; }

    int day() const { return d; }
    int month() const { return m; }
    int year() const { return y; }

    void display() const;   //Print to screen

};

void Date::display() const { 
    cout << d << "." << m << "." << y << endl;
}

Date::Date(int dd, int mm, int yy){
    d = dd;
    m = mm;
    y = yy;
}


For example, the arguments of addDay(const int &dd);. Is that good, or should it just be an integer without const and without reference?

Solution

For built-in types, there is no point in passing it as a const& - prefer a plain int (or a const int) instead.

Other comments:

  • Your add- functions are said to return int even though you don't have a return statement. I don't think that would or should even compile. Change them to void.



  • Take the time to write out day, month and year. The extra seconds in typing is nothing compared to the readability gain.



  • Are you sure you want a default date?



  • Consider overloading operator



  • Consider changing your display() function into a to_string function instead, and have it return a std::string.



  • Make your class easy to use correctly, and hard to use incorrectly. What if month is 12 and someone calls addMonth()? What is someone passes in June as month, but 31 as day? Is day day the day of the month, or day of the year? Adhere to the principle of least astonishment. Your class should behave the way users of the class expect it to.



  • Don't pollute the global namespace with using namespace std.



  • Split the code into a header and an implementation file. Even though you won't need it now, it's good practice. That makes point 7 even more crucial.



You need to make some judgments to design a
Date` class properly. I won't give you any further suggestions, because it is a good exercise to think about it. Revise your code, and think about the pros and cons of various approaches. Apart from that and the points above, your code looks OK.

Context

StackExchange Code Review Q#28339, answer score: 10

Revisions (0)

No revisions yet.