|
Home | Switchboard | Unix Administration | Red Hat | TCP/IP Networks | Neoliberalism | Toxic Managers |
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and bastardization of classic Unix |
Contents : Foreword : Ch01 : Ch02 : Ch03 : Ch04 : Ch05 : Ch06 : Ch07 : Ch08 :
you have a procedure with ten parameters, you probably missed some. —Alan Perlis
Subroutines are one of the two primary problem-decomposition tools available in Perl, modules being the other. They provide a convenient and familiar way to break a large task down into pieces that are small enough to understand, concise enough to implement, focused enough to test, and simple enough to debug.
Use of subroutines helps to make a program more modular, which in turn makes it more adaptable and maintainable. Subroutines also make it possible to structure the actions of programs iether as operations of some abstract machine and/or hierarchically (with several layers of abstraction), which improves the readability of the resulting code.
Some recommendations:
sub coerce;
# and later...
my $expected_count = coerce $input, $INTEGER, $ROUND_ZERO;
But that approach can quickly become much harder to understand:
fix my $gaze, upon each %suspect;
More importantly, leaving off the parentheses on subroutines makes them harder to distinguish from builtins, and therefore increases the mental search space when the reader is confronted with either type of construct. Your code will be easier to read and understand if the subroutines always use parentheses and the built-in functions always don’t:
my $expected_count = coerce($input, $INTEGER, $ROUND_ZERO);
fix(my $gaze, upon(each %suspect));
Some programmers still prefer to call a subroutine using the ancient Perl 4 syntax, with an ampersand before the subroutine name:
&coerce($input, $INTEGER, $ROUND_ZERO);
&fix(my $gaze, &upon(each %suspect));
set_error_handler( \&log_error );
Just use parentheses to indicate a subroutine call:
coerce($input, $INTEGER, $ROUND_ZERO);
fix( my $gaze, upon(each %suspect) );
$curr_pos = tell get_mask();
$curr_time = time & get_mask();And always use the parentheses when calling a subroutine, (like get_mask()). That way it’s immediately obvious that you intend a subroutine call:
curr_obj()->update($status); # Call curr_obj() to get an object,
# then call the update()method on that objectand not a typename:
curr_obj->update($status); # Maybe the same (if currobj() already declared),
# otherwise call update() on class 'curr_obj'
unpack @_ to temp variables if you do not want to change the arguments that were passed to the subroutine
It is often make sense tp use a hash of named arguments for any subroutine that has more than three-five parameters.Subroutines always receive their arguments in the @_ array. But accessing them via $_[0], $_[1], etc. directly is can lead to mistakes unless you really want to change the values that were passes to the subroutnes:
Readonly my $SPACE => q{ };
# Pad a string with whitespace...
sub padded {
# Compute the left and right indents required...
my $gap = $_[1] - length $_[0];
my $left = $_[2] ? int($gap/2) : 0;
my $right = $gap - $left;# Insert that many spaces fore and aft...
return $SPACE x $left
. $_[0]
. $SPACE x $right;
}Using “numbered parameters” like this makes it difficult to determine what each argument is used for, whether they’re being used in the correct order, and whether the computation they’re used in is algorithmically sane. Compare the previous version to this one:
sub padded {
my ($text, $cols_count, $want_centering) = @_;# Compute the left and right indents required...
my $gap = $cols_count - length $text;
my $left = $want_centering ? int($gap/2) : 0;
my $right = $gap - $left;# Insert that many spaces fore and aft...
return $SPACE x $left
. $text
. $SPACE x $right;
}Here the first line unpacks the argument array to give each parameter a sensible name. In the process, that assignment also documents the expected order and intended purpose of each parameter. The sensible parameter names also make it easier to verify that the computation of $left and $right is correct.
A mistake when using numbered parameters:
my $gap = $_[1] - length $_[2];
my $left = $_[0] ? int($gap/2) : 0;
my $right = $gap - $left;is much harder to identify than when named variables are in the wrong places:
my $gap = $cols_count - length $want_centering;
my $left = $text ? int($gap/2) : 0;
my $right = $gap - $left;Moreover, it’s easy to forget that each element of @_ is an alias for the original argument; that changing $_[0] changes the variable containing that argument:
# Trim some text and put a "box" around it...
sub boxed{
$_[0] =~ s{\A \s+ | \s+ \z}{}gxms;
return "[$_[0]]";
}Unpacking the argument list creates a copy, so it’s far less likely that the original arguments will be inadvertently modified:
# Trim some text and put a "box" around it...
sub boxed {
my ($text) = @_;$text =~ s{\A \s+ | \s+ \z}{}gxms;
return "[$text]";
}It’s acceptable to unpack the argument list using a single list assignment as the first line of the subroutine:
sub padded {
my ($text, $cols_count, $want_centering) = @_;# [Use parameters here, as before]
}Alternatively, you can use a series of separate shift calls as the subroutine’s first “paragraph”:
sub padded {
my $text = shift;
my $cols_count = shift;
my $want_centering = shift;# [Use parameters here, as before]
}The list-assignment version is more concise, and it keeps the parameters together in a horizontal list, which enhances readability, provided that the number of parameters is small.
Theshift-based version is preferable, though, whenever one or more arguments has to be sanity-checked or needs to be documented with a trailing comment:
sub padded {
my $text = _check_non_empty(shift);
my $cols_count = _limit_to_positive(shift);
my $want_centering = shift;# [Use parameters here, as before]
}Note the use of utility subroutines (see “Utility Subroutines” in Chapter 3) to perform the necessary argument verification and adjustment. Each such subroutine acts like a filter: it expects a single argument, checks it, and returns the argument value if the test succeeds. If the test fails, the verification subroutine may either return a default value instead, or call croak() to throw an exception (see Chapter 13). Because of that second possibility, verification subroutines should be defined in the same package as the subroutines whose arguments they are checking.
This approach to argument verification produces very readable code, and scales well as the tests become more onerous. But it may be too expensive to use within small, frequently called subroutines, in which case the arguments should be unpacked in a list assignment and then tested directly:
sub padded {
my ($text, $cols_count, $want_centering) = @_;
croak q{Can't pad undefined text} if !defined $text;
croak qq{Can't pad to $cols_count columns} if $cols_count <= 0;# [Use parameters here, as before]
}The only circumstances in which leaving a subroutine’s arguments in @_ is appropriate is when the subroutine:
- Is short and simple
- Clearly doesn’t modify its arguments in any way
- Only refers to its arguments collectively (i.e., doesn’t index@_)
- Refers to@_only a small number of times (preferably once)
- Needs to be efficient
This is usually the case only in “wrapper” subroutines:
# Implement the Perl 6 print+newline function...
sub say {
return print @_, "\n";
}# and later...
say( 'Hello world!' );
say( 'Greetings to you, people of Earth!' );In this example, copying the contents of @_ to a lexical variable and then immediately passing those contents to print would be wasteful.
Better still, use named arguments for any subroutine that is ever likely to have more than three parameters.
Named arguments replace the need to remember an ordering (which humans are comparatively poor at) with the need to remember names (which humans are relatively good at). Names are especially advantageous when a subroutine has many optional arguments—such as flags or configuration switches—only a few of which may be needed for any particular invocation.
Named arguments should always be passed to a subroutine inside a single hash, like so:
sub padded {
my ($arg_ref) = @_;my $gap = $arg_ref->{cols} - length $arg_ref->{text};
my $left = $arg_ref->{centered} ? int($gap/2) : 0;
my $right = $gap - $left;return $arg_ref->{filler} x $left
# and then...
. $arg_ref->{text}
. $arg_ref->{filler} x $right;
}
for my $line (@lines) {
$line = padded({ text=>$line, cols=>20, centered=>1, filler=>$SPACE });
}As tempting as it may be, don’t pass them as a list of raw name/value pairs:
sub padded {
my %arg = @_;my $gap = $arg{cols} - length $arg{text};
my $left = $arg{centered} ? int($gap/2) : 0;
my $right = $gap - $left;return $arg{filler} x $left
. $arg{text}
. $arg{filler} x $right;
}# and then...
for my $line (@lines) {
$line = padded( text=>$line, cols=>20, centered=>1, filler=>$SPACE );
}Requiring the named arguments to be specified inside a hash ensures that any mismatch, such as:
$line = padded({text=>$line, cols=>20..21, centered=>1, filler=>$SPACE});
will be reported (usually at compile time) in the caller’s context:
Odd number of elements in anonymous hash at demo.pl line 42
Passing those arguments as raw pairs:
$line = padded(text=>$line, cols=>20..21, centered=>1, filler=>$SPACE);
would cause the exception to be thrown at run time, and from the line inside the subroutine where the odd number of arguments were unpacked and assigned to a hash:
Odd number of elements in hash assignment at Text/Manip.pm line 1876
It is okay to mix positional and named arguments, if there are always one or two main arguments to the subroutine (e.g., the string thatpadded()is supposed to pad) and the remaining arguments are merely configuration options of some kind. In any case, when there are both positional arguments and named options, the unnamed positionals should come first, followed by a single reference to a hash containing the named options. For example:
sub padded {
my ($text, $arg_ref) = @_;my $gap = $arg_ref->{cols} - length $text;
my $left = $arg_ref->{centered} ? int($gap/2) : 0;
my $right = $gap - $left;return $arg_ref->{filler} x $left . $text . $arg_ref->{filler} x $right;
# and then...
}
for my $line (@lines) {
$line = padded( $line, {cols=>20, centered=>1, filler=>$SPACE} );
}Note that using this approach also has a slight advantage in maintainability: it sets the options more clearly apart from the main positional argument.
By the way, you or your team might feel that three is not the most appropriate threshold for deciding to use named arguments, but try to avoid significantly larger values of “three”. Most of the advantages of named arguments will be lost if you still have to plough through five or six positional arguments first.
Please check back next week for the continuation of this article.
Society
Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers : Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism : The Iron Law of Oligarchy : Libertarian Philosophy
Quotes
War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda : SE quotes : Language Design and Programming Quotes : Random IT-related quotes : Somerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose Bierce : Bernard Shaw : Mark Twain Quotes
Bulletin:
Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 : Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law
History:
Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds : Larry Wall : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOS : Programming Languages History : PL/1 : Simula 67 : C : History of GCC development : Scripting Languages : Perl history : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history
Classic books:
The Peter Principle : Parkinson Law : 1984 : The Mythical Man-Month : How to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite
Most popular humor pages:
Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor
The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D
Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.
FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.
This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...
|
You can use PayPal to to buy a cup of coffee for authors of this site |
Disclaimer:
The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.
Last modified: March, 12, 2019