One of the stylistic 'conventions' I find slightly irritating in published code, is the use of:
if(condition) {
instead of (my preference):
if (condition) {
A slight difference, and probably an unimportant one, but it occurred to me that the first style might be justified if 'if' statements were implemented as a kind of function call. Then I could stop objecting to it.
Does anyone know of a programming language where an if statement is implemented as a function call, where the argument is a single boolean expression?
EDIT: I realise the blocks following the if() are problematic, and the way I expressed my question was probably too naive, but I'm encouraged by the answers so far.
tcl is one language which implements if as a regular in built function/command which takes two parameters ; condition and the code block to execute
if {$vbl == 1} { puts "vbl is one" }
http://tmml.sourceforge.net/doc/tcl/if.html
In fact, all language constructs in tcl (for loop , while loop etc.) are implemented as commands/functions.
It's impossible for it to have a single argument since it has to decide which code path to follow, which would have to be done outside of said function. It would need at least two arguments, but three would allow an "else" condition.
Lisp's if has exactly the same syntax as any other macro in the language (it's not quite exactly a function, but the difference is minimal): (if cond then else)
Both the 'then' and 'else' clauses are left unevaluated unless the condition selects them.
In Smalltalk, an if statement is kind of a function call -- sort of, in (of course) a completely object oriented way, so it's really a method not a free function. I'm not sure how it would affect your thinking on syntax though, since the syntax is completely different, looking like:
someBoolean
ifTrue: [ do_something ]
ifFalse: [ do_something_else ]
Given that this doesn't contain any parentheses at all, you can probably interpret it as proving whatever you wanted to believe. :-)
If the if function is to be a regular function, then it can't just take the condition, it needs as its parameters the block of code to run depending on whether the condition evaluates to true or not.
A prototype for a function like that in C++ might be something along the lines of
void custom_if(bool cond, void (*block)());
This function can either call the block function, or not, depending on cond.
In some functional languages things are much easier. In Haskell, a simple function like:
if' True a _ = a
if' _ _ b = b
allows you to write code like this:
if' (1 == 1)
(putStrLn "Here")
(putStrLn "There")
which will always print Here.
I don't know of any languages where if(condition) is implemented as a regular function call, but Perl implements try { } catch { } etc.. {} as function calls.
Related
You can define a function to pass its keyword arguments to inner functions like this:
function example(data;xcol,ycol,kwargs...)
DoSomething(; spec=:EX, x=xcol, y=ycol, kwargs...)
end
Now, the function DoSomething accepts many arguments, such as color. This works for functions, but I'd like to do this with a macro from VegaLite.jl:
function example(data;xcol,ycol,kwargs...)
#vlplot(data=data,mark=:point, x=xcol, y=ycol,kwargs...)
end
example(df,xcol=:Miles_per_Gallon, ycol=:Horsepower, color=:Origin)
Note that the code above does not work.
So the answer here is... it's tricky. And in fact, in general, this isn't possible unless the macro itself supports it.
See, macros do their transformations at parse time — and often will exploit what you've actually written to mean something different and special. For example, #vlplot will specially handle and support JSON-like {} syntaxes. These aren't valid Julia code and can't be passed to a function you define (like example)!
Now, it's tempting to see this and think, ok, let's make that outer example thing into a macro, too! But it's not that easy. I'm not sure it's possible to have a general answer that will always pass the arguments appropriately and get the hygiene correct. I'm pretty sure you need to know something about how the macro you're calling handles its arguments.
you need to add ; before kwargs to signal they are kwargs not positional arguments e.g.:
DoSomething(;spec=:EX, x=xcol, y=ycol, kwargs...)
(this is the answer for DoSomething being a function as this was the original formulation of the question)
Interesting discussion came up among my peers as to whether or not the "if" statement is considered a method? Although "if" is appended with the word statement it still behaves similar to a simple non-return value method.
For example:
if(myValue) //myValue is the parameter passed in
{
//Execute
}
Likewise a method could perform the same operation:
public void MyMethod(myValue)
{
switch(myValue)
{
case true:
//Logic
break;
case false:
//Logic
break;
}
}
Is it accurate to call (consider) the "if" statement a simple predefined method in a programming language?
In languages such as C, C++, C#, Java, IF is a statement implemented as a reserved word, part of the core of the language. In programming languages of the LISP family (Scheme comes to mind) IF is an expression (meaning that it returns a value) and is implemented as a special form. On the other hand, in pure object-oriented languages such as Smalltalk, IF really is a method (more precisely: a message), typically implemented on the Boolean class or one of its subclasses.
Bottom line: the true nature of the conditional instruction IF depends on the programming language, and on the programming paradigm of that language.
No, the "if" statement is nothing like a method in C#. Consider the ways in which it is not like a method:
The entities in the containing block are in scope in the body of an "if". But a method does not get any access to the binding environment of its caller.
In many languages methods are members of something -- a type, probably. Statements are not members.
In languages with first-class methods, methods can be passed around as data. (In C#, by converting them to delegates.) "if" statements are not first-class.
and so on. The differences are myriad.
Now, it does make sense to think of some things as a kind of method, just not "if" statements. Many operators, for instance, are a lot like methods. There's very little conceptual difference between:
decimal x = y + z;
and
decimal x = Add(y, z);
And in fact if you disassemble an addition of two decimals in C#, you'll find that the generated code actually is a method call.
Some operators have unusual characteristics that make it hard to characterize them as methods though:
bool x = Y() && Z();
is different from
bool x = And(Y(), Z());
in a language that has eager evaluation of method arguments; in the first, Z() is not evaluated if Y() is false. In the second, both are evaluated.
Your creation of an "if" method rather begs the question; the implementation is more complicated than an "if" statement. Saying that you can emulate "if" with a switch is like saying that you can emulate a bicycle with a motorcycle; replacing something simple with something far more complex is not compelling. It would be more reasonable to point out that a switch is actually a fancy "if".
You can't create a myIfStatement() method and expect the following to work:
...
myIfStatement(something == somethingElse)
{
// execute if equal
}
else
{
// execute if different
}
if is a control statement, and cannot be replicated by a method, nor can you replace a method call with if:
myVariable = if(something == somethingElse);
if cannot be overloaded.
These are a few signs that if is not a method, but there are others I suspect.
Depends on the language for sure, but in C, java, perl, no, they're language commands. Reserved words. If they were functions, you'd be able to overload them and get pointers to them and do all the other things that you can do with functions.
This is more of a philiosophical question than a programming question though.
A method has a signature and its main intention is resuable logic, whereas if is simply a condition that controls the flow of execution.
If you understand assembly, you would know that both are different even on a very low level.
You can of course write If() and IfElse() methods but that does not make them the same.
if() is defined as a statement in the language , at the same level as method calls. But there are differences in a.o. syntax and optimization possibilities.
So: No, the if() statement is not a method. You cannot for instance not assign it to a delegate.
Considering the if statement to be a method only makes it confusing, in my opinion. The similarities with a method call is just superficial.
The if statement is one of the statements that control the execution flow. When it's compiled into native machine code, it will evaluate the expression and make a conditional jump.
Pseudo code:
load myValue, reg0
test reg0
jumpeq .skip
; code inside the if
.skip:
If you use else, you will get two jumps:
load myValue, reg0
test reg0
jumpeq .else
; code inside the if
jmp .done
.else:
; code inside the else
.done:
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 it were to be classed as a method then surely we would be in the realms of OO, however we're not, so I'll assume we're on about a function. Certainly a function/subroutine could be written to replicate the if behaviour (I think it is actually a function in lisp/scheme).
I wouldn't class it as a function or even a subroutine though, just control flow.
If by method we understand a block of code that could be called and the control flow automatically returns to the caller when the method ends, then ifs aren't methods. The control flow doesn't return anywhere after an if is executed.
The IF statement is a conditional contruct feature used in most lanuages which executes a path flow from the boolean condition evaluation of true or false. Apart from the case of branch predication, this is always achieved by selectively altering the control flow based on some condition.
The IF construct is the most basic and needed logic used when programming. It allows the building blocks for functions to be introduced.
Yes, if is a function in certain languages, even though it's rare and the uses are limited.
Usually the construct is something like if(booleanCondition, functionPointerToCallIfConditionTrue, functionPointerToCallIfCondtionFalse) This can itself be used as a delegate to other functions if you want.
Mathematica, for example, behaves this way and even C# can do so with a bit of work if you use Linq-expressions; Take a look at System.Linq.Expressions.Expression.IfThenElse.
No. You don't return back when you are finished with an if. It's merely a control statement.
Note that in your example, you replaced one "selection statement" (C# 4 specification, section 8.7), the if statement (section 8.7.1) with another, the switch statement (section 8.7.2). You also refactored the selection statement into a separate method. You haven't replaced the use of a selection statement with a method, however.
The answer to your question is "no".
Let's say that I have a function that should only execute if some constant is defined. which of the following would be better
Option 1: wrap all the function calls in an if block:
if(defined('FOO_BAR_ENABLED')) {
foobar();
}
I figure this way the intent is more clear, but it requires checking the constant every time the function is called.
Option 2: check the constant in the function itself:
function foobar() {
if(!defined('FOO_BAR_ENABLED')) {
return;
}
//do stuff
}
This way requires less lines of code, and the constant is sure to get checked. However, I find it confusing to see calls to this function when it's not actually doing anything. Thoughts?
May I suggest renaming the function to FoobarIfEnabled(), then doing the check in the function?
Stealing liberally from a great language-agnostic answer to one of my own questions, when programming we have the following concerns:
Make it correct.
Make it clear.
Make it concise.
Make it fast. ... in that order.
If you do the check outside the function, you might end up missing it in one place. And if you want to change the behavior, you'll have to find all the places it gets called and fix it. That's a maintenance nightmare which violates principle 1. By adding "IfEnabled" or something like that to the name, now it is not just correct but also is clear. How can you beat that?
Performance is not to be worried about unless the final speed is unsatisfactory and you have identified this as the bottleneck (unlikely).
I recommend you follow the link above and read as it was a very useful answer that gave me much to think about.
Option 3:
void maybe_foobar() {
if(defined('FOO_BAR_ENABLED')) really_foobar();
}
void really_foobar() {
// do stuff
}
On a good day I'd think of better names than "maybe" and "really", but it depends what the function does and why it's turn-off-and-onable.
If there is no circumstance under which anyone could validly "do stuff" when FOO_BAR_ENABLED isn't defined, then I'd go with your option 2 (and perhaps call the function do_stuff_if_possible rather than foobar, if the name foobar was causing confusion as to whether calling it entails actually doing anything). If it's always valid to "do stuff", but some users just so happen do so conditionally, then I'd go with my option 3.
Option 1 is going to result in you copy-and-pasting code around, which is almost always a Bad Sign.
[Edit: here's Option 4, which I suspect is over-engineering, but you never know:
void if_enabled(string str, function f) {
if (defined(str + '_ENABLED')) f();
}
Then you call it with:
if_enabled('FOO_BAR', foobar);
Obviously there's some issues there to do with how your language handles functions, and whether there's any way to pass arbitrary parameters and a return value through if_enabled.]
Does the condition of the if fall within the function's responsibility? Is there a use case for calling the function without the if?
If the condition always needs to be checked, I'd put it in the function. Follow the DRY principle here: Don't Repeat Yourself. Another quip that might be helpful is the SRP - the Single Responsibility Principle - do one thing, and do it well.
In the header file, if foobar always takes the same number of arguments,
#ifdef ENABLE_FOOBAR
#define maybe_foobar(x) foobar(x)
#else
#define maybe_foobar(x)
#endif
Not sure how to do that in C++ or older C dialects if foobar can take a variable number of arguments.
(Just noticed language-agnostic tag. Well, the above technique is what I'd suggest in languages where it works; maybe use an inline function for languages which have those but lack macros).
Option 2, less code and it ensures the constant is defined, as you suggested.
Since this is apparently only used with the foobar() function, then option 2 should be your choice. That means the test is located in only one place and your code is more readable.
Should functions always return something? I often write very basic functions which are used as shorthand to do things that happen a lot such as:
function formsAway() {
$("#login_form, #booking_form").slideUp();
}
Should this function exist - is there a better way, or is this fine?
They don't have to return anything. If you leave it blank it simply returns 'undefined' which in this case is fine because you never intend to use the return value. The Javascript syntax is pretty simplistic and as far as I know there just isn't any real distinction between functions that do and functions that don't return a value (other than the 'return' keyword)
All JavaScript functions return something. If an explicit return is omitted, undefined is returned automatically instead. When a function returns, its instance is wiped out from memory, which also frees all the variables in its scope to be wiped out if nothing else points to them. Without a forced return memory management would have to be done manually.
To my knowledge, unless you need it to return something, a function doesn't have to return anything.
It may be different in other languages, but I've never heard it being necessary or good practice in JavaScript.
Should functions always return
something?
I believe that totally depends on the usage of the function.
is there a better way, or is this
fine?
IMO writing these kind of functions is good when there are many occurrences of the reusable code which can be replaced by the function so that the code looks much cleaner. But only for a couple of occurrences you may just put the code as it is instead of replacing it with function. You should also take into account the chances of reuse of this function in other places in future.
Why can't the conditional operator be used as a statement?
I would like to do something like:
boolean isXyz = ...;
...
isXyz ? doXyz() : doAbc();
where doXyz and doAbc are return void.
Note that this is not the same as other operators, for example doXyz() + doAbc() intrinsically needs that doXyz and doAbc return a number-like something to operate (or strings to concatenate, or whatever, but the point is that + actually needs values to operate on).
Is there something deep or is it just an arbitrary decision.
Note: I come from the Java world, but I would like to know if this is possible in your favourite programming language.
C and C++ do allow such constructs. As long as doXyz() and doAbc() return the same type. Including void.
What would be the point? Why not just use an if statement (which, in my opinion, looks cleaner)?
Because it would reduce readability and introduce a potential for errors.
Languages offer means of doing what you wish by using the keyword "if".
// Is not much longer than the line below
// but significantly more transparent
if (isXyz) doXyz() else doAbc();
isXyz ? doXyz() : doAbc();
A statement is supposed to just perform some operations.
A conditional operator is meant to return a value.
As a novelty, mIRCscripting allows you to do this
alias canI? {
$iif($1 == 1,doThis,doThat)
}
alias doThis echo -a this can.
alias doThat echo -a that can.
calling it with /canI? 1 will echo this can.
calling it with /canI? 2 will echo that can.
Wouldn't this be exactly the same as the if statement?
if (isXyz) doXyz(); else doAbc();
Some languages do allow you to use the conditional operator as a statement. Perl comes to mind.
An expression, including a conditional expression, may be used on its own as a statement in Java and many other languages (I'd go as far as to say most currently-popular languages).
It's specifically ‘void-returning’ in Java that's the issue here, not anything to do with conditionals. It's sometimes considered bad taste to hide active (non-idempotent; with side-effects) code inside an expression, and active functions often return void. So because Java is a prescriptive language, it disallows using a void function in an expression. Many other languages are more permissive and will allow it.
You could get around it by having doAbc and doXyz return something — zero, a boolean, anything: it doesn't matter as long as they're the same type for both, the result will be thrown away in an ExpressionStatement. But I don't really know why you'd want to; as others have said, this is indeed a case where doing it in an expression is in poor taste and largely pointless.
I think your question is the wrong way round.... the conditional operator was added because the "IF THEN" statement couldn't be used as an evaluation statement.
In my option you should only use the conditional operator when conditionally evaluating as it is inherently less clear than using "IF THEN" constructs when purely implementing a condition.
Conditional operators cannot typically contain blocks of multiple instructions on each condition result, "IF THEN" can.