Re: Programming style: using Classes or inline
- From: Grant McLean <grant mclean net nz>
- To: gtk-perl-list gnome org
- Subject: Re: Programming style: using Classes or inline
- Date: Thu, 16 Mar 2006 21:52:20 +1300
On Wed, 2006-03-15 at 21:13 -0600, David wrote:
I first tried to keep my perl source separated into 3 files, all inline
code without making any packages, including the other two into the main
program by "use" statements, but when I added "use strict", I found that
I had to tie the variables to a package, so I just made them all "my
variables" - but, at least as far as I could see, they were not
recognized across files, so I just merged them all into a single file.
No, that's right, before you added 'use strict' all your variables were
global variables. When you declared the variables with 'my', you
restricted their scope to the block they appeared in (eg: a subroutine)
or to the file if they weren't in a block.
Global variables are OK for quick hack scripts but as you code grows it
can become hard to keep track of all the places which might rely on or
alter the value of a global variable.
For a little perspective, my code now occupies some 1500+ lines.
That would benefit from being organised into subroutines at the very
if I were to adapt some of the routines to Classes, what's
normally best - separate files or a single file?
You can do either. It's perfectly reasonable to declare multiple
classes in a single file. If you get to the point that you want to
share a class between two or more programs then splitting it out into a
separate file would be a good idea.
Basically, after all the above, what I'm asking is for some pointers as
to where Classes are beneficial and where not, and the same for multiple
The main benefit is organising your code into manageable chunks to make
code maintenance easier. I'm sure it all makes sense to you now, but if
you come back to it after three months things might not be so clear.
Organising things into subroutines is a good start because you have to
give the subroutines names to describe what they do and you have to
think about what inputs they require and what outputs they return. By
going a step further and making classes and methods, you can store your
program state inside the classes rather than in global variables.
Another advantage to making your code more modular, is that it make it
easier to write tests, but I suspect you're not looking to do that with
you project just yet.
It sounds like you're in the ideal situation of being able to play
around with the code and try different styles without being under
pressure - and what you have already works. So explore a bit. The
perlmonks.org web site is a good place for questions and quick feedback
] [Thread Prev