in reply to Your use of assertions in Perl ?

This isn't a perl specific point, but coders need to be able to distinguish between situations where they should die/assert/explode/etc, and situations where they need to be able to handle the bogus input.

Imagine you're writing a web browser. It connects to some server accross the web, downloads some content and tries to parse it as HTML, images, flash, sound... There's quite a lot of code, so it's useful to add assertions in many functions.

However, you can't add an assertion like this without it failing (pointlessly) on many many sites:

if (m{<body>}) { die "Mismatched tags!" unless m{</body>}; }

In general, only assert over items that you (or someone in your team) is in control of. Never assert about items that you can't control, such as content from the www or a user - you'll just have to find some way of coping with errors in that.

Oh, and remember that you'll need to be able to tell the difference, and that there shouldn't be a gap between the things that are asserted and the things that are handled...

Replies are listed 'Best First'.
Re^2: Your use of assertions in Perl ?
by AZed (Monk) on Sep 19, 2008 at 20:34 UTC
    Never assert about items that you can't control, such as content from the www or a user - you'll just have to find some way of coping with errors in that.

    I'd modify that to, "Never assert about items that neither you or your intended users can control." An assertion is a perfectly valid way to inform a user, "stop mangling your input data", though you are right of course in that it is nothing more than a source of frustration if the point of the code is for users to run it on someone else's arbitrary and potentially mangled input data.

    As a corollary, however, I'd add that it's nice if your error message tells the user as much as possible about what was wrong and how to fix it.