This site tickled my sense of humour - http://www.antiifcampaign.com/ but can polymorphism work in every case where you would use an if statement?
There is nothing wrong with using if-statements, but avoiding them can sometimes make the code a bit more readable to humans. This is definitely not a general rule as sometimes avoiding if-statements will make the code a lot less readable. You be the judge. Avoiding if-statements is not just about readability.
An if statement looks at any and every thing in the parentheses and if true, executes block of code that follows. If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed.
Smalltalk, which is considered as a "truly" object oriented language, has no "if" statement, and it has no "for" statement, no "while" statement. There are other examples (like Haskell) but this is a good one.
Quoting Smalltalk has no “if” statement:
Some of the audience may be thinking that this is evidence confirming their suspicions that Smalltalk is weird, but what I’m going to tell you is this:
An “if” statement is an abomination in an Object Oriented language.
Why? Well, an OO language is composed of classes, objects and methods, and an “if” statement is inescapably none of those. You can’t write “if” in an OO way. It shouldn’t exist. Conditional execution, like everything else, should be a method. A method of what? Boolean.
Now, funnily enough, in Smalltalk, Boolean has a method called ifTrue:ifFalse: (that name will look pretty odd now, but pass over it for now). It’s abstract in Boolean, but Boolean has two subclasses: True and False. The method is passed two blocks of code. In True, the method simply runs the code for the true case. In False, it runs the code for the false case. Here’s an example that hopefully explains:
(x >= 0) ifTrue: [ 'Positive' ] ifFalse: [ 'Negative' ]
You should be able to see ifTrue: and ifFalse: in there. Don’t worry that they’re not together.
The expression (x >= 0) evaluates to true or false. Say it’s true, then we have:
true ifTrue: [ 'Positive' ] ifFalse: [ 'Negative' ]
I hope that it’s fairly obvious that that will produce ‘Positive’.
If it was false, we’d have:
false ifTrue: [ 'Positive' ] ifFalse: [ 'Negative' ]
That produces ‘Negative’.
OK, that’s how it’s done. What’s so great about it? Well, in what other language can you do this? More seriously, the answer is that there aren’t any special cases in this language. Everything can be done in an OO way, and everything is done in an OO way.
I definitely recommend reading the whole post and Code is an object from the same author as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With