Im new to c++, I'm reading the core guidelines and I came across this:
P.1: Express ideas directly in code
In this, it says to use something like Month month() const; instead of int month();
So I have 2 questions, why is there a const at the end of the function and what does that do? And how is Month defined? Can you declare new functions with any name instead of things like int, double, float etc?
Thanks in advance
The point of the guideline is what it says: to put the ideas behind the interface in the code itself.
If you have some date type, and it has a member function
int month();, that expresses the idea that you can retrieve a month from the date. And presumably, the returnedintvalue represents the month of the year as stored within that date.But... how does it represent the month? It's an integer. Is the month of January given the integer 0, as might be expected by a long-time programmer (of most languages)? Or maybe it is given the integer 1, because that's how dates are actually written? The code itself says nothing about this; you would have to look at the documentation for the function to find out. So if you see
if(date.month() == 1), you don't know if the code is asking if it is January or February.The alternative,
Month month() const;returns the typeMonth. Now, what that type is is not specified. Whatever it is, that type can make it unambiguous what value is represented by "January". For example:How is "January" encoded? By the enum value
Month::January. Therefore, if you see the testif(data.month() == Month::January), then it is clear exactly what it is saying. It is not only unambiguous, it also reads almost exactly like English: is the month of the date the month of January.This is what it means to express an idea in the code: the entirety of the idea is unambiguously expressed by the code. Make the code say what it is doing, not-so-much how it is doing it.