[Catalyst] best practice: where to put constants

Jarom Smith jarom at jaromsmith.net
Thu Jun 4 15:20:23 GMT 2009


Hi all:

This is probably my lack of Perl knowledge showing... but where would be
the best-practice place to put constants in my code?  I'm talking about
magic numbers that I use internally but need to reference in multiple
locations of the code.  Things like

     "VENDOR_COMMIT" => 1,
     "VENDOR_DECLINE" => 2,
     "TIME_OUTSIDE_WINDOW" => 3,

In Java I would declare them as "public static final" members the class
that describes that particular object (in this case, a vendor
notification) and I would refer to them like

     if (notification.getAction() == Notification.VENDOR_COMMIT) ....

So I think the analog to that in Catalyst would be to define the
constant(s) in the ResultSource classes that are automatically generated
for me (below the line) and then refer to them like

     if ($notification->action == 
MyApp::Schema::ResultSet::Notification::VENDOR_COMMIT) ....

The problem with doing it that way is that the namespace starts to 
become unwieldly, and I have to remember where I put the thing I'm 
trying to reference.  The alternative would be to put them at the top 
level, i.e., in MyApp.pm:

     use constant NOTIFICATION_VENDOR_COMMIT => 1;
     use constant NOTIFICATION_VENDOR_DECLINE => 2;
     use constant NOTIFICATION_TIME_OUTSIDE_WINDOW => 3;

     use constant NOTIFICATION_PROPERTY_ACCEPT => 1;
     use constant NOTIFICATION_PROPERTY_CANCEL => 2;
     use constant NOTIFICATION_PROPERTY_OFFER_NEW_WINDOW => 3;

and then in the code I just say

     if ($notification->action == MyApp::VENDOR_COMMIT) ....

In the end, this is what I decided to do because I have relatively few 
of these guys (so far) and I'd rather have them thrown together all in 
one place than spread all over the system.  But I'm wondering if there 
is a best practice?

I don't want to put them in the config hash or in a configuration file
because these are not things that a user should be able to change or 
override.

Thanks in advance for the advice/insight; this group has been a great 
help so far.

jarom smith
tech go-to guy





More information about the Catalyst mailing list