Search code examples
crefactoringpebble-watch

How to make it more beautiful?


Example code from the application for the Pebble watch. The code works and outputs a timer between two timestamp, but how to make it more beautiful?

char d[5];
char h[5];
char m[5];
char s[5];
const char *start = "START";

time_t now_time = time(NULL);
int tt = other_time - now_time;

if (tt > 0) {
    int rest = tt % 31556926;
    int dd = rest / 86400;
    rest = tt % 86400;
    int hh = rest / 3600;
    rest = tt % 3600;
    int mm = rest / 60;
    int ss = rest % 60;

    if (dd > 0) 
        snprintf(d, sizeof(d), "%dD", dd);
    else
        snprintf(d, sizeof(d), "%s", "\n");
    ...
    if (ss > 0)
        snprintf(s, sizeof(s), " %dS", ss);
    else
        snprintf(s, sizeof(s), "%s", "\n");

    snprintf(string, sizeof(string), "%s%s%s%s", d, h, m, s);  
} else {
    snprintf(string, sizeof(string), "%s", start);
}

Solution

  • If by "beautiful" you mean "elegant" (which is usually taken as "concise and efficient"), I would try something like:

    #include <stdio.h>
    #include <time.h>
    
    char * getDuration(time_t future)
    {
        char * duration = (char *) malloc(sizeof(char) * 32);
        int elapsed = (int) (future - time(NULL));
        if(elapsed > 0)
        {
            int d = (elapsed % 31556926) / 86400;
            int h = (elapsed %    86400) /  3600;
            int m = (elapsed %     3600) /    60;
            int s = (elapsed %       60)        ;
            sprintf(duration, "%sD%sH%sM%sS", d, h, m, s);  
        }
        else sprintf(duration, "START");
        return duration;
    }
    

    PS: I didn't get why you were printing "\n" in the strings instead of "0D", "0H" etc.