KBD

Keith Devens .com

Sunday, October 12, 2008 Flag waving
When your enemy is making a very serious mistake, don't be impolite and disturb him. – Napoleon Bonaparte (allegedly)
← Why do Wiki RSS Feeds Suck? (by Jeremy Zawodny)Wiki spam →

Daily link icon Friday, January 7, 2005

Concise code

You may have gotten the sense that I highly value concise code, what with me making a big deal about wasting a line for a curly brace and quoting my favorite Dijkstra quote all the time.

Just now I took Natalie's time_since() code, which I've been using for a long while to print the English dates on my blogroll (thanks again Nat!), and shortened it a bit. I find it amusing how different it got:

<?php
function time_diff($now$then){
    if((
$since abs($now $then)) < 60) return '< 1 minute';
    
$names = array('year','month','week','day','hour','minute');
    
$intervals = array(
        
60 60 24 365
        
60 60 24 30,
        
60 60 24 7,
        
60 60 24,
        
60 60,
        
60,
    );
    
    
$n=0$c=count($names);
    while(
$n<$c and ($r=floor($since/$intervals[$n])) == 0$n++;
    
$print "$r {$names[$n]}"; if($r 1$print .= 's';

    if(++
$n<$c and $r=(floor(($since $r*$intervals[$n-1]) / $intervals[$n]))){
        
$print .= ", $r {$names[$n]}"; if($r 1$print .= 's';
    }
    return 
$print;
}
?>

Update: I changed $count to $r (for "remainder") so it would fit without wrapping.

Update: Added a line to er, modified (the first line of) the code, see comments for details.

← Why do Wiki RSS Feeds Suck? (by Jeremy Zawodny)Wiki spam →

Comments XML gif

Richard@Home (http://richardathome.no-ip.com) wrote:

Concise code is good, but its definitely lost some readability :-(

∴ Richard@Home | 7-Jan-2005 9:22am est | http://richardathome.no-ip.com | #6792

Justin wrote:

You don't use && instead of and?

∴ Justin | 7-Jan-2005 10:13am est | #6794

Keith (http://keithdevens.com/) wrote:

Concise code is good, but its definitely lost some readability :-(

See, to me I think it's gained readability. For the first one I thought that there was all this code for me to understand, so I never really looked at it. Now it's down to essentially two expressions for me to have to comprehend. I think that's much easier.

You don't use && instead of and?

The only language I use && in are languages that don't support and. Why, do you prefer && in all cases?

Keith | 7-Jan-2005 1:21pm est | http://keithdevens.com/ | #6795

Ben (http://www.trollscript.de/blog) wrote:

"&&" and "and" have different operator precedence in PHP. This fact can bite you && be very difficult to track down. Look at this little snippet and compare the different output:

$a = true;
$b = false;

$c = $a and $b;
$d = $a && $b;

print "c: $c\n";
print "d: $d\n";

I never use the "and" operator in PHP due to this nasty circumstance. It's too easy to forget, so I stick with the one that produces the obvious result.

Regarding your concise code: It is of course a question of personal preferences. I do agree with Richard that Natalie's version is more readable and easier to comprehend. Personally, I favor consistency more than conciseness, so I always use braces after if or while statements, and use whitespace between operators too make it... more readable, duh. Smiley winking

You did not only make the code more concise, you also added more functionality. I particularly like the decision to send a second time parameter into the function to serve as a reference point for the "now" time. That allows you too compute time differences with future dates as well, and makes your version more versatile to use. Thumbs up for that.

There is a small glitch in your code however: If I call it like this

time_diff(time(), time() - 5);

your code produces an error notice, and the return value is not that meaningful. Natalie's version can cope with this time, and produces "0 minutes" as the return value. I'd like to provide a fix, but my first attempt screwed even more up, and I'm supposed to be working right now instead. Smiley

∴ Ben | 7-Jan-2005 1:52pm est | http://www.trollscript.de/blog | #6799

Keith (http://keithdevens.com/) wrote:

It's too easy to forget, so I stick with the one that produces the obvious result.

Oh, whenever I assign the result of a logical expression to a variable I always put it in parens. So, it's funny -- we've chosen different consistencies. Smiley However, and is the lower precedence one, so that's usually what you want in a condition.

That allows you too compute time differences with future dates as well, and makes your version more versatile to use.

Thanks for noticing Smiley winking (The arguments can also be in either order, which is nice). I originally started modifying the code for that very reason -- I wanted it to handle dates in the future for my new "countdowns" section on the right. Though after trying it, I decided I'd rather have the countdown just count in days. Also, not that it's terribly important, but this version is more efficient as well -- you don't call time() on each iteration, there are only two arrays vs 7, you don't have multiple nested array accesses in the loops, and it uses fewer temporaries.

There is a small glitch in your code

Thanks for pointing out my bug. It seems my translation of the code wasn't exact if the interval is < 60 seconds. The easiest way to handle that case was to add if($since < 60) return '< 1 minute'; as a special case. I like that better too. While the original code produced '0 minutes', this now produces "< 1 minute" in that case.

Keith | 7-Jan-2005 2:56pm est | http://keithdevens.com/ | #6800

Feel free to post a comment below. Please see my comment policy.

Formatting Rules (No HTML):

  • **bold**, *italic*, _underlined_, --strikeout--
  • "text"="url" creates a link, and URLs are auto-highlighted
  • Blockquote: Like e-mail, begin paragraph with > (greater-than sign)
  • Lists: begin paragraph with *,-, or + (unordered), or # (ordered)
  • Code block: ?!code:language=perl|php|sql|javascript|etc.{\n}...{\n}?!/code

:
(will be your IP address if blank)
: (optional)
(Will not be shown on site)

: (optional)
:

October 2008
SunMonTueWedThuFriSat
 1234
567891011
12131415161718
19202122232425
262728293031 



RSS feed RSS feed for Keith's Weblog
Atom feed Atom feed for Keith's Weblog
Weblog archive
Recent comments
  on 7 posts

Recent comments XML

I hate PHP

Elliot Anderson,

Dude!! You the​man! The reverse replacement for​array_u...

Alex Ndungu: Oct 11, 1:35am

Call a function from a string in Python

?!code:
some_object.__getattribute​__('method_name')()
?!/code

is​the s...

Patrick Corcoran: Oct 8, 3:53pm

Spider solitaire

I have won 185 games of Spider​Solitaire at the "Difficult" level.​ What is...

75.179.28.113: Oct 8, 12:42pm

Sed one-liners

Hi.

I wanted to let you know​that I wrote an article "Famous Sed​One-Lin...

Peteris Krumins: Oct 8, 3:05am

Timesheet Calculator

Hadn't seen it before now, but my​company already uses a time​tracking prog...

Keith: Oct 7, 10:44am

Girls, please don't get breast implants

Hey everyone, 

I am new to this​blog and I have enjoyed reading all​your...

Sarah.M.: Oct 6, 9:45am

Generated in about 0.268s.

(Used 8 db queries)

mobile phone