Page 1 of 1

var == 'value' vs 'value' == var

Posted: Sat May 20, 2017 12:13 pm UTC
by Yu_p
Another webcomic [1] brought up a little convention-ambiguity, that I was thinking about sometimes when writing emacs lisp; So I wondered what you prefer :)

Personally, for the simple "variable equals value" case I always use the variant with variable name first, since in most cases this occurs for me in if/elif/cond blocks that are, at least partly, the logical equivalent of a switch block. The second variant I use sometimes with "<" in lisp, as the prefix notation throws me off in this case if I mix ">" and "<", e.g.

Code: Select all

(and (< 0 x) (< x 10))


Otherwise I only use the second variant if the comparison isn't constant-to-variable but constant-to-expression, e.g.

Code: Select all

(eq 'idle (cdr (assq 'state process-info))) ; I use this in lisp
if process_info.state == "idle": ...        # But not in python
if (process_info.state == "idle") { ...     // or C-inspired languages

but not even then if it is python.

[1] http://www.commitstrip.com/en/2014/01/2 ... e-syntaxe/

Re: var == 'value' vs 'value' == var

Posted: Sat May 20, 2017 1:29 pm UTC
by Flumble
No idea why you would put the variable on the right side (if it is an expression with a left-hand side and a right-hand side and one of the hands is a variable). Clearly you want to match the variable to some expression, so when reading the variable should come first.
If you want to know whether some expression (possibly with variables) matches a constant, the constant usually goes on the right.

Re: var == 'value' vs 'value' == var

Posted: Sat May 20, 2017 1:46 pm UTC
by Sizik
I think the two reasons this would be done are that in C, it prevents accidental assignment due to a typo:

Code: Select all

// Compiles (although some compilers give a warning)
if(x = 0) { ... }

// Compile error
if(0 = x) { ... }


And in Java, you can avoid a null pointer exception if you're using the .equals() method when comparing an object against a known non-null value:

Code: Select all

// NPE if foo is null
if(foo.equals("bar")) { ... }

// NPE not possible
if("bar".equals(foo)) { ... }

Re: var == 'value' vs 'value' == var

Posted: Sun May 21, 2017 12:09 am UTC
by Tub
Sizik wrote:I think the two reasons this would be done are that in C, it prevents accidental assignment due to a typo:

It's useless in C, because:

Code: Select all

 /tmp> gcc -Werror=parentheses test.c
test.c: In function 'main':
test.c:4:2: error: suggest parentheses around assignment used as truth value [-Werror=parentheses]
  if (x = 0)
  ^~
cc1: some warnings being treated as errors

Code: Select all

 /tmp> clang -Werror=parentheses test.c
test.c:4:8: error: using the result of an assignment as a condition without parentheses [-Werror,-Wparentheses]
        if (x = 0)
            ~~^~~
test.c:4:8: note: place parentheses around the assignment to silence this warning
        if (x = 0)
              ^
            (    )
test.c:4:8: note: use '==' to turn this assignment into an equality comparison
        if (x = 0)
              ^
              ==
1 error generated.

Enabling the error is easier than writing unreadable code all over.

I've only seen the switched style once, in a php project. The project no longer exists, though I cannot prove a relation between coding guidelines and the project's demise.

Re: var == 'value' vs 'value' == var

Posted: Sun May 21, 2017 1:54 am UTC
by Soupspoon
It may be (relatively) hard work to swap round existing statements as prophylative against errors (that you might as well just check, for, and leave alone all those you found to be cofrectly done) but when syarting from scratch... It's not a useless practice to get into doing automatically. Even back in the '80s when learning Pascal (where assignment was := and equivalence was = on its own) I heard advocacy of using the "if <static> is what <variable> is" construction, almost as a mantra. And in that language I don't even recall it being a legal move that an assignment can be made and its success (e.g. that it didn't fail due to being NaN or otherwise out of type, regardless lf overloading) then immediately appropriated by a branching/looping decision. I presume that the tutor concerned probably came to the habit from some different language.

Maybe that was C? In various C flavours, assignments occurring and then broadcasting truths about themselves are a valid (if occasionally dickishly obfuscating) shortcut. Maybe deprecated in more contemporary implementations. But, as an e.g., the perlish "while (my $nextline = <$filehandle>) {chomp $nextline; …}" is pretty much a commonly understood (if not globally used) convention for that language, even though TIMTOWTDI naturally still rules and countless other methods (with greatermor lesser readability) could be employed in its stead, even before going down the OO route.

(Though I think you do get non-fatal warnings reported, if so "use"d, for "if ($x=$y) {…}" where it is likely a typo of ommitance. And I tend to default to "eq" instead of "==" in the appropriate (textish) circumstances, which removes the honest-typo issue for a downright fail error if I miss either character of "eq" and fail to spot it before running.)

Also, might aid readability:

Code: Select all

if (var1  == x*y) …
if (var2  == sqrt(width) …
if (var3a == funnyFunction(i,familyCounter,refRelTree) …
if (var3b != var3a) …

Re: var == 'value' vs 'value' == var

Posted: Mon May 22, 2017 1:18 am UTC
by Xanthir
Yu_p wrote:The second variant I use sometimes with "<" in lisp, as the prefix notation throws me off in this case if I mix ">" and "<", e.g.

Code: Select all

(and (< 0 x) (< x 10))

A bit off-topic, but just so you know, < is an n-ary function in Lisp, so you can just write (< 0 x 10) for that kind of thing. The only reason to ever split it into two bits is if you need < on one and <= on the other. (And in that case, I agree with your ordering.)

Re: var == 'value' vs 'value' == var

Posted: Mon May 22, 2017 9:58 am UTC
by PM 2Ring

Re: var == 'value' vs 'value' == var

Posted: Fri Jul 14, 2017 6:11 pm UTC
by Bloopy
I fondly recall watching a colleague write a Yoda condition in SQL, but the funny part was that my boss is a self-taught programmer and didn't expect it to work at all.

After many years of dealing with data which has unique IDs, I'm a bit rusty on .equals, but that one might actually be useful on occasion. My surprise moment when implementing a .equals method for the first time in forever was re-learning that objects of the same class can peek at each other's private parts.

Re: var == 'value' vs 'value' == var

Posted: Sun Jul 23, 2017 1:00 am UTC
by Arancaytar
I think 'value' == var is a dumb relic of times when we had to rely on syntax errors instead of IDEs with code inspections, not to mention automated tests.

It's annoying to read, and I can't remember a single time where an accidental assignment bug was difficult to diagnose, instead of being immediately obvious in its effect.

Re: var == 'value' vs 'value' == var

Posted: Fri Aug 04, 2017 5:20 pm UTC
by Thesh
Arancaytar wrote:I think 'value' == var is a dumb relic of times when we had to rely on syntax errors instead of IDEs with code inspections, not to mention automated tests.


It's a relic from a language without type-safe Booleans.

Re: var == 'value' vs 'value' == var

Posted: Mon Aug 07, 2017 8:13 pm UTC
by Xanthir
No, you get the problem even if you throw away the concept of "truthy/falsey", if the accidental assignment was of a boolean value.

Re: var == 'value' vs 'value' == var

Posted: Tue Aug 08, 2017 8:32 pm UTC
by chridd
Xanthir wrote:No, you get the problem even if you throw away the concept of "truthy/falsey", if the accidental assignment was of a boolean value.
...but that's less common, because most values aren't boolean and if a value is boolean you can just say if(var) or if(!var).

Re: var == 'value' vs 'value' == var

Posted: Tue Aug 08, 2017 10:24 pm UTC
by Xanthir
Yeah, that's a reasonable retort. Anyone who does "foo() == true" is making a mistake in the first place. ^_^

So, make the following fixes:

1. if() (and loops) *only* accepts actual bools.
2. == and != does *not* accept bools (instead it throws an error saying to just use the value itself, or negate it)
3. There's some way to cast to a bool, like a "bool()" function, for when you do need truthy/falsey values.
4. There's some way to test equality of bools, like an "equal()" function, for when you do need it.

This avoids all the problems, while still allowing the useful pattern of setting something in the condition part of a loop or an if. (Python loses this by making = a statement, which isn't allowed in those places.)

The downside is that it's now slightly trickier to compare two arbitrary values using ==, as you have to remember not to compare bools. I only compare bools in very rare circumstances, when two operations both return a bool and I need to see if they return same/different values. (That said, I could instead be using and/or/xor for these things, which are explicitly about bools.)

Re: var == 'value' vs 'value' == var

Posted: Tue Aug 08, 2017 10:42 pm UTC
by Demki
Xanthir wrote:Yeah, that's a reasonable retort. Anyone who does "foo() == true" is making a mistake in the first place. ^_^


I've seen that used in C# where foo() returns (bool?) as shorthand for:

Code: Select all

bool? x = foo(); 
if(x != null && x.Value)
  // ...

or

Code: Select all

bool? x = foo(); 
if(x.HasValue && x.Value)
  // ...


then again, I am pretty sure that in this case if(x = true) will not compile, as it can't implicitly convert bool? to bool.

Re: var == 'value' vs 'value' == var

Posted: Tue Aug 08, 2017 11:04 pm UTC
by EvanED
Xanthir wrote:2. == and != does *not* accept bools (instead it throws an error saying to just use the value itself, or negate it)
You "can't" do this; if (b1 == b2) is a reasonable thing to want to say, and IMO making Booleans a second-class citizen is the wrong way to solve this "problem." In particular, languages with C++-ish templates would suffer immensely from this obfuscation, because you would usually be unable to use == inside templates; ditto for dynamically-typed languages.

I actually think the right way to solve this problem in a C-like language you're designing is a modification of the Clang -Wall -Werror approach. Under those rules: if (a = b) is a syntax error, if ((a = b)) is what you right if you really want the assign-then-check behavior, if ((a == b)) is a syntax error (contrasting with GCC). I would make one modification: I wouldn't allow just if ((a = b)) -- in the case where you want to assign a bool in a conditional, I think it's reasonable to require an explicit comparison, as in if ((a = b) == true), if (!(a = b)), or (less so) if (!!(a = b)) or if ((bool)(a = b)).

Re: var == 'value' vs 'value' == var

Posted: Tue Aug 08, 2017 11:22 pm UTC
by Xanthir
Hmm, yeah, "tainting" the result of an assignment such that it can't be used directly as a boolean would work even better. The tautology operator (!!) is always there for you.

Re: var == 'value' vs 'value' == var

Posted: Wed Aug 09, 2017 11:07 am UTC
by Sandor
EvanED wrote:((a = b)) is what you write if you really want the assign-then-check behavior

I like C's comma operator for assign-then-check behavior, for example like this:

Code: Select all

while (a = func(), a != 0) {
  /* Do stuff with a */
}

It also works for more complicated cases as well.

Re: var == 'value' vs 'value' == var

Posted: Wed Aug 09, 2017 2:53 pm UTC
by speising
2 much typing

Re: var == 'value' vs 'value' == var

Posted: Wed Aug 30, 2017 7:40 am UTC
by Derek
Sandor wrote:
EvanED wrote:((a = b)) is what you write if you really want the assign-then-check behavior

I like C's comma operator for assign-then-check behavior, for example like this:

Code: Select all

while (a = func(), a != 0) {
  /* Do stuff with a */
}

It also works for more complicated cases as well.

I prefer to use for for this.

Code: Select all

for (a = func(); a != 0; a = func())