in reply to Subroutines versus straight top to bottom scripts

Maintainability generally. Comprehension improves when information is in chunks that map onto an abstract model of what the process is doing. Its much easier to understand a program where dataflow only happens by argument passing and where subroutines are as minimalistic as is reasonably possible. Even when your script is pretty well unreusable its a lot easier to extend and maintain if you can ignore large chunks of the code because they are in subroutines clearly named as not being relevent to the issue at hand.

For instance lets say we have a program that scans a bunch of files and generates some stats. We could put the whole process into a single sub or not even use one, but it would be a lot easier to understand if we could just look at main and see what it does:

sub main { my @files=get_files(...); my $stats=scan_files(\@files); print_stats($stats); return 0; } exit(main());

---
$world=~s/war/peace/g

Replies are listed 'Best First'.
Re^2: Subroutines versus straight top to bottom scripts
by wazoox (Prior) on Jun 03, 2005 at 10:07 UTC
    I understand your point. I have myself a further problem : I write quite big applications (several -- up to 50 -- thousand lines). A typical program have hundreds of subs. Some subs are only called from other subs, which are called by other subs, .... which are called from main. How would you split that? Should I write a different package for each "big enough" sub?
      That depends entirely on the circumstances and what all the subs do. If, for example, you have a group of subs that all do one thing or another with a given set of data, then it could be worth the trouble to turn said set of data into an object and treat the subs that go along with it as methods but once again, that depends entirely on the context within which one is working. I myself almost exclusively use OO style perl but that just so happens to be because the things I generally work with can easily be translated to an OO style of thinking. Could you elaborate a bit on what kind of subroutines we're talking about?


      Remember rule one...
      I have constructed my programs so that they consist of a main() sub which made up of a list of smaller subroutines.
      Each line of the main() is commented.

      The effect is similar to a novel with the main equivalent to a list of chapters with the sub routines making up like the contents of a book.

      Also when I need to check any part of the program I can see in the main where about it is
      and can quickly "find" to the sub.

      Making changes updating or removing is made alot easier especially when there are no inner subroutines.

      Of course not all the sub routines are listed in main() as some are within called with others