Order of items being compared? - comparison

I've seen this around, but never heard a clear explanation of why... This is really for any language, not just C# or VB.NET or Perl or whatever.
When comparing two items, sometimes the "check" value is put on the left side instead of the right. Logically to me, you list your variable first and then the value to which you're comparing. But I've seen the reverse, where the "constant" is listed first.
What (if any) gain is there to this method?
So instead of:
if (myValue > 0)
I've seen:
if (0 < myValue)
or
if (Object.GimmeAnotherObject() != null)
is replaced with:
if (null != Object.GimmeAnotherObject())
Any ideas on this?
TIA!
Kevin

Some developers put the constant on the left like so
if(0 = myValue)
This is because you will get an error from the compiler, since you can't assign 0 a value. Instead, you will have to change it to
if(0 == myValue)
This prevents lots of painful debugging down the road, since typing
if(myValue = 0)
is perfectly legal, but most likely you meant
if(myValue == 0)
The first choice is not what you want. It will subtly change your program and cause all sorts of headaches. Hope that clarifies!

I don't think a simple rule like but the constant first or but the constant last is not a very smart choice. I believe the check should express it semantics. For example I prefer to use both versions in a range check.
if ((low <= value) && (value <= high))
{
DoStuff(value);
}
But I agree on the examples you mentioned - I would but the constant last and can see no obviouse reason for doing it the other way.
if (object != null)
{
DoStuff(object);
}

In C++ both these are valid and compile
if(x == 1)
and
if(x=1)
but if you write it like this
if(1==x)
and
if(1=x)
then the assignment to 1 is caught and the code won't compile.
It's considered "safer" to put the const variable on the left hand side.
Once you get into the habit of putting the const variable on the left for assignment it tends to become your default mode of operation, that's why you see it showing up in equality checks as well

For .Net, it's irrelevant, as the compiler won't let you make an assignment in a condition like:
if(x=1)
because (as everyone else said) it's bad practice (because it's easy to miss).
Once you don't have to worry about that, it's slightly more readable to put the variable first and the value second, but that's the only difference - both sides need to be evaluated.

Its a coding practice to catch typos like '!=' typed as '=' for example.
If you have a CONSTANT on the left all assignment operators will be caught by the compiler since you cannot assign to a constant.
Many languages (specifically C) allow a lot of flexibility in writing code. While, the constant on the left seems unusual to you, you can also program assignments and conditionals together as,
if (var1 = (var2 & var3)) { /* do something */ }
This code will get the boolean result into var1 and also /* do something */ if the result is true.
A related coding practice is to avoid writing code where conditional expressions have assignments within them; though the programming language allows such things. You do not come across such code a lot since assignments within conditionals is unusual so typical code does not have such things.
There is a good C language coding practices article at the IBM DeveloperWorks site that is probably still relevant for people writing in that language.

Related

Which is the quicker operator in objective c

I use == and != a lot in my code and I was wondering which is quicker in objective c so that I can make my app as fast as possible.
Situation
I have a variable which is one of two things and I want the quickest method to see which one it is
Thanks in advance
You should not worry about this level of detail for performance reasons, unless you've identified a performance issue.
However, wondering to satisfy an inquiring mind is a different matter! :-) The answer is they are identical.
A comparison is usually compiled as an instruction which sets condition flags; this could be a specific comparison instruction or something like an arithmetic instruction which sets condition codes; followed by a conditional jump which tests the condition flags - and a test for "equal" is the same cost as for "not equal", just a different setting of those condition flags.
This also means that statements such as if([some method call]) ... and if(![some method call]) ... have the same cost - the "not" operator produces no extra code.
You can test yourself.
Check current milliseconds before and after operating.
I guess there's no differences..
If you really need to know,
you could make a lot of operating with loop.
then you will get the answer.
This is silly. You would have to execute millions of iterations of code using the 2 versions of if statement in order to even detect a difference in speed. This is a triviality, and not worth worrying about.
As the other poster said, == and != should take exactly the same amount of time for non-floatingpoint values. For floating point, there might be some differences, since for an equal comparison the processor has to first normalize the 2 floating point values, then compare them, and normalizing is relatively time-consuming. I don't know if testing for non-equality if slower than equality. IT's unlikely but not impossible.

Why is it that Lua doesn't have augmented assignment? [duplicate]

This is a question I've been mildly irritated about for some time and just never got around to search the answer to.
However I thought I might at least ask the question and perhaps someone can explain.
Basically many languages I've worked in utilize syntactic sugar to write (using syntax from C++):
int main() {
int a = 2;
a += 3; // a=a+3
}
while in lua the += is not defined, so I would have to write a=a+3, which again is all about syntactical sugar. when using a more "meaningful" variable name such as: bleed_damage_over_time or something it starts getting tedious to write:
bleed_damage_over_time = bleed_damage_over_time + added_bleed_damage_over_time
instead of:
bleed_damage_over_time += added_bleed_damage_over_time
So I would like to know not how to solve this if you don't have a nice solution, in that case I would of course be interested in hearing it; but rather why lua doesn't implement this syntactical sugar.
This is just guesswork on my part, but:
1. It's hard to implement this in a single-pass compiler
Lua's bytecode compiler is implemented as a single-pass recursive descent parser that immediately generates code. It does not parse to a separate AST structure and then in a second pass convert that to bytecode.
This forces some limitations on the grammar and semantics. In particular, anything that requires arbitrary lookahead or forward references is really hard to support in this model. This means assignments are already hard to parse. Given something like:
foo.bar.baz = "value"
When you're parsing foo.bar.baz, you don't realize you're actually parsing an assignment until you hit the = after you've already parsed and generated code for that. Lua's compiler has a good bit of complexity just for handling assignments because of this.
Supporting self-assignment would make that even harder. Something like:
foo.bar.baz += "value"
Needs to get translated to:
foo.bar.baz = foo.bar.baz + "value"
But at the point that the compiler hits the =, it's already forgotten about foo.bar.baz. It's possible, but not easy.
2. It may not play nice with the grammar
Lua doesn't actually have any statement or line separators in the grammar. Whitespace is ignored and there are no mandatory semicolons. You can do:
io.write("one")
io.write("two")
Or:
io.write("one") io.write("two")
And Lua is equally happy with both. Keeping a grammar like that unambiguous is tricky. I'm not sure, but self-assignment operators may make that harder.
3. It doesn't play nice with multiple assignment
Lua supports multiple assignment, like:
a, b, c = someFnThatReturnsThreeValues()
It's not even clear to me what it would mean if you tried to do:
a, b, c += someFnThatReturnsThreeValues()
You could limit self-assignment operators to single assignment, but then you've just added a weird corner case people have to know about.
With all of this, it's not at all clear that self-assignment operators are useful enough to be worth dealing with the above issues.
I think you could just rewrite this question as
Why doesn't <languageX> have <featureY> from <languageZ>?
Typically it's a trade-off that the language designers make based on their vision of what the language is intended for, and their goals.
In Lua's case, the language is intended to be an embedded scripting language, so any changes that make the language more complex or potentially make the compiler/runtime even slightly larger or slower may go against this objective.
If you implement each and every tiny feature, you can end up with a 'kitchen sink' language: ADA, anyone?
And as you say, it's just syntactic sugar.
Another reason why Lua doesn't have self-assignment operators is that table access can be overloaded with metatables to have arbitrary side effects. For self assignment you would need to choose to desugar
foo.bar.baz += 2
into
foo.bar.baz = foo.bar.baz + 2
or into
local tmp = foo.bar
tmp.baz = tmp.baz + 2
The first version runs the __index metamethod for foo twice, while the second one does so only once. Not including self-assignment in the language and forcing you to be explicit helps avoid this ambiguity.

RunOnce in Foreach

I'm writing a little scripting language just for a bit of fun and the learning of the codes :P
I would just like your opinions/suggestions. I have an idea but I don't want to include something that people are going to want to spit on. I plan on making this language open source once, soon.
Does anybody think that it would be cool to have something like:
[Foreach] Uppercase Letter s
in Case-Insensitive Word SallySawtheSeafiShandateit:
Count++.
s.Highlight: True.
RunOnce.ProtectedMethod.ActivateProtectedMethod: IsTrue.
[Protected Method.LockTo: [Foreach]].IsTrue
StatusBar.Message: Match for s was found. Total: Count..
RunOnce.ProtectedMethod.Disable.
Explanation: What the above actually does is it searches through a string of text "SallySawtheSeafiShandateit" and highlights every single match. But when it finds the very first match for "s", it runs a method called "IsTrue", and sets the statusbar text to "match was found...". And then deactivates the RunOnce method so it may no longer be accessed, since there's no need for it to be run again.
This might not be the best example, but I think you get the idea. There have been plenty of times where I've needed to do something only once in a foreach loop, but couldn't, without writing a whole bunch of other code.
I figure, atleast this way, everything can be done in just two methods.
Please be brutally honest. :)
Thank you
This just seems like an over-complication of the following structure (in java style):
boolean ranOnce = false;
for (char c : string.toCharArray()) {
if (c != 's') continue;
if (!ranOnce) {
// do stuff once
ranOnce = true;
}
// do other stuff
}
It just seems like extreme over-engineering to me, when a single boolean and an if condition do the trick.
Hm. For this sort of situation I'd normally just use a flag variable and a conditional.
I'd reconsider "runOnce" -- it's a little ambiguous. Does it run the first iteration, the last iteration, somewhere in the middle? From what I can tell it looks like yours runs in the very first iteration, but then again what use would displaying the total count be in the first iteration? You'll know it's just "1".
For my money, I think I'd actually use two keywords that fired events/methods/etc at the first iteration and at the last iteration, respectively.

Recommended initialization values for numbers

Assume you have a variety of number or int based variables that you want to be initialized to some default value. But using 0 could be problematic because 0 is meaningful and could have side affects.
Are there any conventions around this?
I have been working in Actionscript lately and have a variety of value objects with optional parameters so for most variables I set null but for numbers or ints I can't use null. An example:
package com.website.app.model.vo
{
public class MyValueObject
{
public function MyValueObject (
_id:String=null,
_amount:Number=0,
_isPurchased:Boolean=false
)
{ // Constructor
if( _id != null ) this.id = _id;
if( _amount != 0 ) this.amount = _amount;
if( _isPurchased != false ) this.isPurchased = _isPurchased;
}
public var id:String;
public var amount:Number;
public var isPurchased:Boolean;
}
}
The difficulty is that using 0 in the above code might be problematic if the value is not ever changed from its initial value. It is easy to detect if a variable has a null value. But detecting 0 may not be so easy because 0 might be a legitimate value. I want to set a default value to make the parameter optional but I also want to later detect in my code if the value was changed from its default without hard to debug side affects.
I suppose I could use something like -1 for a value. I was wondering if there are any well known coding conventions for this kind of thing? I suppose it depends on the nature of the variable and the data.
This is first my stack overflow question. Hopefully the gist of my question makes sense.
A lot of debuggers will use 0xdeadbeef for initializing registers. I always get a chuckle when I see that.
But, in all honesty, your question contains its own answer - use a value that your variable is not ever expected to become. It doesn't matter what the value is.
Since you asked in a comment I'll talk a little bit about C and C++. For efficiency reasons local variables and allocated memory are not initialized by default. But debug builds often do this to help catch errors. A common value used is 0xcdcdcdcd which is reasonably unlikely. It has the high bit set and is either a rather large unsigned or rather large negative signed number. As a pointer address it is odd which will cause an alignment exception if used on anything but a char (but not on X86). It has no special meaning as a 32 bit floating point number so it isn't a perfect choice.
Occasionally you'll see a partially aligned value in a variable such as 0xcdcd0000 or 0x0000cdcd. These can be treated as suspcious at the very least.
Sometimes different values will be used depending on the allocation area of library. That gives you a clue where a bad value may have originated (i.e., it itself wasn't initialized but it was copied from an unititialized value).
The ideal value would be invalid no matter what alignment you read from memory and is invalid over all primitive types. It also should look suspicious to a human so even if they do not know the convention they can suspect something is a foot. That's why 0xdeadbeef can be a good choice because the (hex viewing) programmer will recognize that as the work of a human and not random chance. Note also that it is odd and has the high bit set so it has that going for it.
The value -1 is often traditionally used as an "out of range" or "invalid" value to indicate failure or non-initialised data. Then again, that goes right down the pan if -1 is a semantically valid value for the variable...or you're using an unsigned type.
You seem to like null (and for a good reason), so why not just use it throughout?
In ActionScript you can only assign Number.NaN to variables that are typed Number, not int or uint.
That being said, because AS3 does not support named arguments you can always look at the arguments array (it's a built-in array that all functions have, unless you use the ...rest construct). If that array's length is less than the position of your numeric argument you know it wasn't passed in.
I often use a maximum value for this. As you say, zero often is a valid value. Generally max-int, while theoretically valid, is safe to exclude. But not always; be careful.
I like 0xD15EA5ED, it's similar to 0xDEADBEEF but is usually more accurate when debugging.

Assignment and condition evaluation in one step

I have this code
def errorMap = validateParams(params)
if (errorMap) {
flash.errorMap = errorMap
return
}
My question is this: Can I combine the assignment in line #1 and evaluation of the condition in line#2 to make a one liner like the following:
if (flash.errorMap = validateParams(params)) {
return
}
Is it a bad practice to do this?
Thanks
Vijay Kumar
We are indoctrinated in C-like languages that single-equals "=" should look like a typo in an if statement. Using a syntax where the single-equals is doing what you mean makes it harder to spot the typo cases.
Although you certainly can do this, my own two cents is that it's usually a bad practice. It's terse, but your if statement is now relying on the evaluation of the assignment, which may not be immediately obvious when you come back and revisit this code months later.
In my opinion it's a very good practice. Calling the function and testing its return value should be thought of together, and putting them together in the source code helps to do that. If you do this habitually, it becomes essentially impossible to accidentally call the function but leave out the code check whether it succeeded.
If this is C++ or C# code, you can combine assignment and evaluation of condition. Just be absolutely certain to avoid using assignment (=) instead of comparison (==). You can waste hours figuring it out.
Also, be careful about using conditions that modify their parameters.
For example,
if (x++ > 100) doStuff()
vs
if (x+1 > 100) doStuff()
While the code in isolation looks precise and elegant, an assignment operator (=) inside the if-clause is more likely to be overlooked as the more prevalent comparison operator (==), which will then cause you more problems.
I wouldn't use it in practice. It could make a good multiple-choice question though.

Resources