When a fat comma is confusing

I frequently swap out commas for fat commas ( => ) when I think it reads better. One place this bites me in the ass is when I reread code where I'm using a function that takes two parameters but look like they could take more. This recently happened to me with Test::LWP::UserAgent.

I started with the docs' example:

$test_ua->map_response(
  "myapp",
  sub { HTTP::Response->from_psgi($app->($_[0]->to_psgi)) },
);

Then thought this would look prettier:

$test_ua->map_response(
  myapp =>
  sub { HTTP::Response->from_psgi($app->($_[0]->to_psgi)) },
);

Then of course I came back two days later and added:

$test_ua->map_response(
  myapp =>
  sub { HTTP::Response->from_psgi($app->($_[0]->to_psgi)) },
  myotherapp => 
    sub { HTTP::Response->from_psgi($app->($_[0]->to_psgi)) },
);

It took me at least an hour to figure that one out. I haven't extracted a real life lesson out of this yet.. I'd be tempted to never use fat commas for a function that expects positional parameters... but I'm not going to start rewriting all my Moo(se) classes to

has 'bah', ( is => 'ro', );

2 Comments

heh, I thought about having map_response and some of the other interfaces accept more parameters, so as to add multiple mappings at once, but I never implemented it because of "YAGNI" - figuring it would be pretty easy for the caller to make two calls instead. Maybe I should have done that after all. :)

On the other hand, sub signatures would be able to give a warning if you passed 4 arguments into a method that expected only 2...

Leave a comment

About Samuel Kaufman

user-pic CTO / Codemonkey, Socialflow.com