So on the one hand, we have something like Perl 6's
.Str function. Trying to implement that any way other than a virtual method calling mechanism would be insanity, because you want code to be able to call that function from anywhere and get the proper result no matter what kind of object you are calling it on. You want to be able to say "The answer is $a" without using some obscene string of ifs based on the type of $a. That's a no brainer.But on the other hand, consider converting a surface object from a nice surface class hierarchy into another surface format which the original class hierarchy can't know anything about. "Aha," the anti-if zealot says, "an opportunity for the Visitor pattern!"
I went through a phase of heavy Visitor pattern usage back around 1997 or so. And in retrospect, I'm pretty sure nine out of ten times I used it, the code would have been better had I just used an if statement; frequently much better.
Here's a quick example: suppose I'm processing a
$surface, and I'd like to use exact calculations if it's a (dead simple) plane surface, and approximate calculations otherwise. So I'm looking to set $use_exact_calculations as appropriate. Here's my best attempt (untested!) to capture the Visitor pattern in Perl 6:If you think this is wordy, you should see the C++ version! Perl 6 is very good at this sort of thing. But still you're creating an entire class just for one usage, and in the process moving critical logic away from the place the logic is actually used.
But would you really rather have that in your code just so you can get rid of this:
Okay, technically that doesn't actually have an if statement, but it does have the dreaded direct examination of the type of
$surface, which is what they would like to eliminate the ifs to avoid.Okay, now. Does anyone seriously think the former code is better than the latter?