Periods and such from strings
Posted by Luigi Ballabio-4 on Apr 26, 2002; 8:31am
URL: http://quantlib.414.s1.nabble.com/Periods-and-such-from-strings-tp2020.html
Hi all,
some idle Friday afternoon thoughts:
Andre's addition of Period(std::string) was a welcome one.
(note to Andre: it might want some more checks on the passed string, though.
Right now, Period("dummy") parses succesfully as 0 years :)
However, I wonder if such functionalities should be made available as
external functions and not as methods of the class itself. This is part due
to simmetry with classes such as DateFormatter which provide conversion
from a date to its string representation externally, and not as a method of
Date itself; and part due to the consideration that things could easily get
messy.
An example: it would be convenient to have the same functionality for
dates, so that one could initialize a Date from, say, "12/5/2002". But is
the latter May 12th or December 5th? I would like to be able to answer "it
depends on what the user wants", meaning that _you_ choose the convention
which should be followed. To do this, we could write a DateParser class to
which a locale is set containing the rules to be used for parsing: support
for more date formats would be added by writing a new locale and plugging
it in. The same locales could then be used in DateFormatter to write dates
in the desired format, rather than the built-in US format we have now. Mr.
Smith would see Christmas as "December 25th", while Sig. Rossi would see it
as "25 Dicembre".
Implementing the above is not that messy, but it is a bit on the heavy side
in terms of lines of code. Therefore, I'd rather keep things as slim as
possible and separate concerns; namely, keep Date focused on date
arithmetics and delegate formatting and dealing with locales to external
classes (DateFormatter and DateParser or whatever we call it). The same
could be done for Period, which in principle could benefit from locales too
(i.e., the Italian short-hand for "2 days" would be "2gg"). But for the
same reason, I would move the functionality in an external class/function
(and also because a plain structure such as Period with two data members
and the corresponding inline accessors---maybe 10 lines of code---would
look a bit unbalanced to me if we attached a few times as much code for
parsing :) The overloaded constructor could be given back by a one-liner
such as
explicit Period::Period(const std::string& s) {
*this = PeriodParser::parse(s);
}
which might not be terribly efficient, but then again, I/O never is. I
don't expect the above to be a bottleneck if we're already reading the
strings from a file.
Thoughts?
Bye,
Luigi