Is the “if” statement considered a method?
No, it's not considered a method as you may have already seen in the other answers. However, if your question were - "Does it behave like a method?", then the answer could be yes depending on the language in question. Any language that supports first-class functions could do without an in-built construct/statement like if
. Ignore all the fluffy stuff like return values and syntax, as basically it is just a function that evaluates a boolean value and if it is true
, then it executes some block of code. Also ignore OO and functional differences because the following examples can be implemented as a method on the Boolean
class in whatever language is being used like Smalltalk does it.
Ruby supports blocks of executable code that can be stored in a variable and passed around to methods. So here's a custom _if_
function implemented in Ruby. The stuff within the { .. }
is a piece of executable code that's passed to the function. It's also known as a block in Ruby.
def _if_ (condition)
condition && yield
end
# simple statement
_if_ (42 > 0) { print "42 is indeed greater than 0" }
# complicated statement
_if_ (2 + 3 == 5) {
_if_ (3 + 5 == 8) { puts "3 + 5 is 8" }
_if_ (5 + 8 == 13) { puts "5 + 8 is 13" }
}
We can do the same thing in C, C++, Objective-C, JavaScript, Python, LISP, and many other languages. Here's a JavaScript example.
function _if_(condition, code) {
condition && code();
}
_if_(42 > 0, function() { console.log("Yes!"); });
if(x)
bad coding style. It "looks" a lot like a function call, even though it isn't. Same forfor(...)
andwhile(..)
.switch()
should be a method too, after all you could just do a method that performed the same operation (maybe usingif
? :))