Archive:
Subtopics:
Comments disabled |
Wed, 11 Jul 2018 Here is another bit of Perl code:
The idea here is that we are expecting A relatively minor problem is that if someone passes an object with no
But the real problem here is that the function's interface is not simple enough. The function needs the string. It should insist on being passed the string. If the caller has the string, it can pass the string. If the caller has a cookie object, it should extract the string and pass the string. If the caller has some other object that contains the string, it should extract the string and pass the string. It is not the job of this function to know how to extract cookie strings from every possible kind of object. I have seen code in which this obsequiousness has escalated to
absurdity. I recently saw a function whose job was to send an email.
It needs an
Here the function needs an But that string could be passed in any of Oh, and by the way, that string might not be a string! It might be the actual object, so there are actually seven possibilities:
Notice that if We hope by the end of this rigamarole that All this because this function was not prepared to insist firmly that its arguments be passed in a simple and unambiguous format, say like this:
I am not certain why programmers think it is a good idea to have functions communicate their arguments by way of a round of Charades. But here's my current theory: some programmers think it is discreditable for their function to throw an exception. “It doesn't have to die there,” they say to themselves. “It would be more convenient for the caller if we just accepted either form and did what they meant.” This is a good way to think about user interfaces! But a function's calling convention is not a user interface. If a function is called with the wrong arguments, the best thing it can do is to drop dead immediately, pausing only long enough to gasp out a message explaining what is wrong, and incriminating its caller. Humans are deserving of mercy; calling functions are not. Allowing an argument to be passed in seven different ways may be
convenient for the programmer writing the call, who can save a few
seconds looking up the correct spelling of Novice programmers may ask “But what if this is business-critical code? A failure here could be catastrophic!” Perhaps a failure here could be catastrophic. But if it is a catastrophe to throw an exception, when we know the caller is so confused that it is failing to pass the required arguments, then how much more catastrophic to pretend nothing is wrong and to continue onward when we are surely ignorant of the caller's intentions? And that catastrophe may not be detected until long afterward, or at all. There is such a thing as being too accommodating. [Other articles in category /prog/perl] permanent link |