IMHO, you certainly need to validate any data coming from an external or uncontrolled source (user input, input file, database, network socket, etc.).

But there is no point checking things that cannot happen. If you know for sure that you have populated an array with some known data and pass that array as an argument to a subroutine, there is usually no point for the subroutine to check whether the array is not empty or has the right data. This may sound obvious, but there is a lot of code out there double checking or triple checking things. Overly defensive programming can be a source of bugs, increased maintenance costs and performance degradation.

Having said that, if there is a chance that the subroutine gets called from somewhere else in the code in the future, it might still be desirable to make sure your arguments really contain what they are supposed to contain. Especially, if your routine is part of a module that may be called by another program, you certainly need to check the validity of the parameters, because you usually can't rely on your module user to do the right thing. The next question is what you should do if they are not valid (should you die, raise an exception, return undef, etc.), and it is sometimes not easy to determine the best course of action in such cases.

In brief, there is no definite answer, it depends often on the actual situation. And there are often some trade-offs. You probably have to use your good judgment.

But all this is just my personal opinion.


In reply to Re: Is validation of all subroutine arguments overkill? by Laurent_R
in thread Is validation of all subroutine arguments overkill? by nysus

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.