I have a rather specific question.
Say I am at the end of a function, and am determining whether to return true or false.
I would like to do this using an if/else statement, and have two options: (examples are in pseudocode)
1) Check if worked first:
if(resultVar != error){
return true;
}else{
return false;
}
2) Check if it failed first:
if(resultVar == error){
return false;
}else{
return true;
}
My question is simple: Which case is better (faster? cleaner?)?
I am really looking at the if/else itself, disregarding that the example is returning (but thanks for the answers)
The function is more likely to want to return true than false.
I realize that these two cases do the exact same thing, but are just 'reversed' in the order of which they do things. I would like to know if either one has any advantage over the other, whether one is ever so slightly faster, or follows a convention more closely, etc.
I also realize that this is extremely nitpicky, I just didn't know if there is any difference, and which would be best (if it matters).
Clarifications:
A comparison needs to be done to return a boolean. The fact that of what the examples are returning is less relevant than how the comparison happens.
This is by far the cleanest:
return resultvar != error;
The only difference in both examples may be the implementation of the operator. A != operator inverses the operation result. So it adds an overhead, but very small one. The == is a straight comparison.
But depending on what you plan to do on the If/else, if there is simply assigning a value to a variable, then the conditional ternary operator (?) is faster. For complex multi value decisions, a switch/case is more flexible, but slower.
This will be faster in your case:
return (resultVar == error) ? false : true;
This will depend entirely on the language and the compiler. There is no specific answer. In C for instance, both of these would be encoded rather like:
return (resultVar!=error);
by any decent compiler.
Put true first, because it potentially eleiminates a JUMP command in assembly. However, the difference is negligible, since it's an else, rather than an else if. There may /technically be a difference/, but you will see no performance difference in this case.
Related
What is the most readable way of writing a very simple function that is effectively executing one statement, if a condition is met?
What I find most readable is this:
function doSomething(myNumber){
if(myNumber !== null && myNumber > 5){
doTheThing();
}
}
However, my colleague insists that guard clauses make anything more readable, and would always write this function like this:
function doSomething(myNumber){
if(myNumber === null || myNumber <= 5)
return;
doTheThing();
}
I understand that guard clauses can be way more readable in bigger functions, especially if there is a need to check for multiple conditions, and/or if exceptions need to be thrown. But in a case like this, I always have to do a triple-take to understand in which case doTheThing() will be executed, which seems ridiculous for such a simple function.
This is not really a technical question, but rather a choice of style.
There are many ways you can write that function and the compiler will try to optimise it as best as possible. As for "readability" this is purely up to the programmer's choice. As long as you follow the language rules and standards, then any choice is fine. Of course if you work in a team it might be better to agree on a certain style, so that everyone can work on the code without getting confused.
Personally, if I really want to make it readable I would do this:
function doSomething(myNumber)
{
if(myNumber != null && myNumber > 5)
{
doTheThing();
}
}
On the other hand if I want less lines of code I would choose this:
function doSomething(myNumber) {
if(myNumber == null || myNumber <= 5) return;
doTheThing();
}
Also it is important to consider how the if statement should be. In this case you cover all possibilities, but just keep it in mind to avoid unexpected errors.
I am wondering, what scenario would be best ?
(Please bare with my examples, these are just small examples of the situation in question. I know you could have the exact same function without a result variable.)
A)
public String doSomthing(){
String result;
if(condition){ result = "Option A";}
else{ result = "Option B";}
return result;
}
B)
public String doSomthing(){
String result = "Option B";
if(condition){ result = " Option A";}
return result;
}
Cause in scenario B: if the condition is met, Then you would be assigning result a value twice.
Yet in code, i keep seeing scenario A.
Actually, the overhead here is minimal, if any, considering the compiler optimisations. You would not care about it in a professional coding environment, unless you are writing a compiler yourself.
What is more important, considering (modern) programming paradigms, is the code style and readability.
Example A is far more readable, as it has a well-presented reason-outcome hierarchy. This is important especially for big methods, as it saves the programmer lots of analysis time.
If I had literally 1000s of simple if statements or switch statements
ex:
if 'a':
return 1
if 'b':
return 2
if 'c':
return 3
...
...
Would the performance of creating trivial if statements be faster when compared to searching a list for something? I imagined that because every if statement must be tested until the desired output is found (worst case O(n)) it would have the same performance if I were to search through a list. This is just an assumption. I have no evidence to prove this. I am curious to know this.
You could potentially put these things in to delegates that are then in a map, the key of which is the input you've specified.
C# Example:
// declare a map. The input(key) is a char, and we have a function that will return an
// integer based on that char. The function may do something more complicated.
var map = new Dictionary<char, Func<char, int>>();
// Add some:
map['a'] = (c) => { return 1; };
map['b'] = (c) => { return 2; };
map['c'] = (c) => { return 3; };
// etc... ad infinitum.
Now that we have this map, we can quite cleanly return something based on the input
public int Test(char c)
{
Func<char, int> func;
if(map.TryGetValue(c, out func))
return func(c);
return 0;
}
In the above code, we can call Test and it will find the appropriate function to call (if present). This approach is better (imho) than a list as you'd have to potentially search the entire list to find the desired input.
This depends on the language and the compiler/interpreter you use. In many interpreted languages, the performance will be the same, in other languages, the switch statements gives the compiler crucial additional information that it can use to optimize the code.
In C, for instance, I expect a long switch statement like the one you present to use a lookup table under the hood, avoiding explicit comparison with all the different values. With that, your switch decision takes the same time, no matter how many cases you have. A compiler might also hardcode a binary search for the matching case. These optimizations are typically not performed when evaluating a long else if() ladder.
In any case, I repeat, it depends on the interpreter/compiler: If your compiler optimized else if() ladders, but no switch statements, what it could do with a switch statement is quite irrelevant. However, for mainline languages, you should be able to expect all constructs to be optimized.
Apart from that, I advise to use a switch statement wherever applicable, it carries a lot more semantic information to the reader than an equivalent else if() ladder.
What is the meaning of a || between two function call
like
{
//some code
return Find(n.left,req)||Find(n.right,req);
}
http://www.careercup.com/question?id=7560692
can some one help me to understand . Many thanks in advance.
It means that it returns true if one of the two functions is true (or both of them).
Depends on the programming language, the method calls Find(n.left,req) -> if it's true - returns true. if it's false, it calls Find(n.right,req) and returns its Boolean value.
In Java (and C and C#) || means "lazy or". The single stroke | also means "or", but operates slightly differently.
To calculate a||b, the computer calculates the truth value (true or false) of a, and if a is true it returns the value true without bothering to calculate b, hence the word "lazy". Only if a is false, will it checks b to see if it is true (and so if a or b is true).
To calculate a|b, the computer works out the value of a and b first, then "ors" the answers together.
The "lazy or" || is more efficient, because it sometimes does not need to calculate b at all. The only reason you might want to use a|b is if b is actually a function (method) call, and because of some side-effect of the method you want to be sure it executes exactly once. I personally consider this poor programming technique, and on the very few occasions that I want b to always be explicitly calculated I do this explicitly and then use a lazy or.
Eg consider a function or method foo() which returns a boolean. Instead of
boolean x = a|foo(something);
I would write
boolean c=foo(something);
boolean x = a||c;
Which explicitly calls foo() exactly once, so you know what is going on.
Much better programming practice, IMHO. Indeed the best practice would be to eliminate the side effect in foo() entirely, but sometimes that's hard to do.
If you are using lazy or || think about the order you evaluate it in. If a is easy to calculate and usually true, a||b will be more efficient than b||a, as most of the time a simple calculation for a is all that is needed. Conversely if b is usually false and is difficult to calculate, b||a will not be much more efficient than a|b. If one of a or b is a constant and the other a method call, you should have the constant as the first term a||foo() rather than foo()||a as a method call will always be slower than using a simple local variable.
Hope this helps.
Peter Webb
return Find(n.left,req)||Find(n.right,req);
means execute first find {Find(n.left,req)} and return true if it returns true or
execute second find return the value true if it return true, otherwise false.
Very simple question:
Specifically in Python (since Python actually has "strongly recommended" style guidelines specified in PEP 8, but really this applies to any language), should a function with an if clause that always returns have the alternative code in an else clause or not? In other words, func_style_one() and func_style_two() in the following piece of code are (obviously) exactly equivalent:
def func_style_one():
if some_conditional_function():
do_something()
return something()
else:
do_something_else()
return something_else()
def func_style_two():
if some_conditional_function():
do_something()
return something()
do_something_else()
return something_else()
Obviously, the best and most readable style depends on the situation, and opinions will vary greatly on which is better, but I'm asking which is specifically preferred by the core Python community. (e.g. Which is used more often in the standard library, all other things being equal?)
As a rule of thumb, you should always avoid adding unneccessary complexity to your code, whatever the language. It also often is a good idea to try to split your code into semantically meaninful subsections.
Given these heuristics, there is no definitive answer. It really boils down to what you are trying to achieve.
I'll demonstrate this with examples.
If we have a function that checks for various error conditions before proceeding, it could make sense to write it without else:
def do_stuff():
if error1():
return cleanup_and_fail()
return ok()
This is better as you often end up checking several errors in similar fashion in a sequence:
def do_stuff():
if error1():
return cleanup_and_fail()
if error2():
return do_different_cleanup_and_fail()
return ok()
However, if your function instead branches to two equal branches, it could semantically make more sense to you else:
def do_stuff():
if option1():
return do_option1()
else:
return do_option2()
This is because you often end up adding several other options with elif:
def do_stuff():
if option1():
return do_option1()
elif:
return do_option2()
else:
return do_option3()
To summarize: think about the semantics of your code and choose syntax accordingly.