views:

153

answers:

5

In our product we have a big utilities file that we require (with do) at the beginning of a lot of our files. Is there a reason not to turn this into a module? For example, instead of doing this:

do '../dbi_utilities.pl';
our ($db,$user,$pw,$attr);
my $Data = DBI->connect($db,$user,$pw,$attr) or die "Could not connect to database: $DBI::errstr";

Couldn't I just do this?:

use AppUtil;
my $Data = AppUtil->connect();

What are the pros and cons of each style?

+2  A: 

Making a module out of it will make it a lot more robust. Right now a lot of things informally depend on each other, but those dependencies aren't immediately obvious.

Also, it would enable you to import only part of the utilities.

Leon Timmermans
+5  A: 

With do(), you're loading and compiling the utilities.pl file each time, which may cause problems if you do() it more than once. Also, use is done at compile which will allow your program to fail sooner, or even be tested with perl -wc.

Lastly, keeping it in a package allows you to protect it's namespace, which can be helpful as your project grows.

I would advise strongly to turn your utilites.pl into a proper Perl package that is loaded with use.

bmdhacks
+1  A: 

You get all of the cool module stuff, encapsulation, module specific functions, and so on.

Notice though, by using use with your syntax. creating an object for the AppUtil namespace, and calling the connect subroutine. for your utilities.

Also you must have 1; at the end of your file.


Sticking with the other method means you don't have to change any code, you don't have to add 1 at the end.

All "do", "use", and "require" import, but scope code that is within them (except named subroutines cause they can't be hidden).

J.J.
Making something into a module doesn't magically give you any features. You have to code it correctly. Also note that do and require *do not* import automatically.
brian d foy
@brian: Your right. It is up the tho programmer to code in the functionality.
J.J.
+8  A: 

The only reason not to do this is time.

That is, it'll take time to clean up your interface, as well as all calling apps to use the new interface.

What it'll cost you in time now will be more than made up when you start using proper tests ("make test" or "./Build test" or just "prove ...") and be able to check that your changes won't break anything before checking it in. So, by all means, convert. Just be aware that it's not a free gain.

Tanktalus
+7  A: 

By making your code into a module with proper refactoring, you make it easy to test. I talk about this in my "Scripts as Modules" article for The Perl Journal as well as "How a Script Becomes a Module" on Perlmonks.

Good luck,

brian d foy