[erlang-questions] how to make beautifulll code of this working code

Richard A. O'Keefe ok@REDACTED
Tue Aug 11 05:50:03 CEST 2015


On 11/08/2015, at 3:46 am, Roelof Wobben <r.wobben@REDACTED> wrote:
> As a working programm I have wrote this :
> 
> -module(dates).
> 
> -export([date_parts/1]).
> 
> date_parts(Date)->
>   [Year, Month, Day] = re:split(Date, "-", [{return, list}] ),
>   [element(1, string:to_integer(Year)), element(1,string:to_integer(Month)), element(1,string:to_integer(Day))].

There are two things about this that I don't like.

One is the repeated element(1, string:to_integer(___)).
As you probably know,
 > string:to_integer("roelof").
 {error,no_integer}
so the element(1,...) thing might return 'error', not an integer.
It would be better to use list_to_integer/1 so that you either
get an integer or an exception.

The other is that I'd rather the list_to_integer/1 function
_didn't_ raise an exception.  You're using regular expressions.
So why not check for digits?

So I'd be looking for a match to
    "^([1-9][0-9][0-9][0-9])-([1-9][0-9]?)-([1-9][0-9]?)$"
so that once the match succeeds you *know* there are
vaguely plausible integers there.

I'm also unhappy that the date is not validated, so that
with your code, "0-0-0" and "42-137-999999" are accepted.

There are at least two kinds of beauty for code:
 - INTERFACE beauty
 - IMPLEMENTATION beauty.

For me, interface beauty means that the function either
gives me clean answers I don't have to worry about any
further or crashes with a useful report, and there are
no nasty glitches I have to worry about.

There is a glitch in your function.
My reading of ISO 8601 is that -0054-8-8 should be a
valid date.  (Using the "retrospective" or "proleptic"
Gregorian calendar.)  But your function will reject it.
If that is what you WANT, that's fine, but you should SAY.
A comment like

% This accepts YYYY-MM-DD dates for 1900 < YYYY < 2100.

would do.

For the purposes of interface beauty, to the *user* of
this function there is no real difference between a
date that is invalid because it looks like "1-2-3-4"
and a date that is invalid because it looks like
"2015-02-29".  So interface beauty would seem to require

%   is_valid(Y, M, D) is true when 1900 < Y < 2100 and
%   Y-M-D is a valid date.

is_valid(Y, M, D) when
    is_integer(Y), 1900 < Y, Y < 2100,
    is_integer(M),    0 < M, M < 13,
    is_integer(D),    0 < D, D < 32
 -> ... in this range, is_leap_year(Y) <=> Y mod 4 = 0






More information about the erlang-questions mailing list