[Purdue-pm] function parameter order question

Mark Senn mark at purdue.edu
Thu Sep 26 11:30:05 PDT 2019


Dave Jacoby wrote:
|  If you have a function that's going to read a file and return the output,
|  and perhaps trigger special behavior if no permissions or file doesn't
|  exist or something, how would you handle parameters?
|
|  What I am engaging right now looks like this.
|
|      read_this_file( $special , $output, $input );
|
|  Where $output is an arrayref.
|
|  What I think is a better way of doing this is
|
|      $output = read_this_file( $input , $special );
|
|  With the signatures feature in more recent Perls, you can set the signature
|  like
|
|      sub read_this_file ( $input , $special = 1 ) { ... }
|
|  so that it defaults to the wanted behavior, or reverse it or not. Of
|  course, with old syntax, you could also do it.
|
|  sub read_this_file {
|      my $file = shift;
|      my $special = shift;
|      $special //= 1;
|      ...
|  }
|
|  So it's more the question of param syntax than function header syntax.
|
|  Do any of you have strong behavior?

OF THE CHOICES ABOVE

Of the choices above I would do
    $output = read_this_file($input, $special);

If I WERE WRITING THE CODE FROM SCRATCH

Because I list arguments in temporal order I would list $input
before $output if both were arguments.

When programming I like to handle error conditions right away
so I don't have to worry about them later in the program.

If I were writing code from scratch to do this I'd probably do
    if ($special = ReadFile($fn, $output))  {
        # (I always use $fn as an abbreviation for "file name".)
        # Handle whatever special is complaining about
        # so I don't have to think about it anymore.
    }
    # rest of code goes here

I don't like using "_" in names.  Perl 6 allows "-", just like COBOL, I
think that's much better than "_".  I usually use camel case, in Perl 5
for my sub names.  In this example the "R" and "F" are the camel's humps
because they're higher than the surrounding characters.
If forced to use $special as an argument I would put it last.
    $output = ReadFile($fn, $special)

(In Wolfram Language where all the system functions are in camel case
I use all lowercase for my functions.)

-mark


More information about the Purdue-pm mailing list