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

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

For conditionals I use...

if var == 'value' / (eq var 'value)
43
100%
if 'value' == var / (eq 'value var)
0
No votes
 
Total votes: 43

Yu_p
Posts: 44
Joined: Wed Oct 12, 2011 9:00 am UTC

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

Postby Yu_p » Sat May 20, 2017 12:13 pm UTC

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/

User avatar
Flumble
Yes Man
Posts: 1944
Joined: Sun Aug 05, 2012 9:35 pm UTC

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

Postby Flumble » Sat May 20, 2017 1:29 pm UTC

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.

User avatar
Sizik
Posts: 1158
Joined: Wed Aug 27, 2008 3:48 am UTC

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

Postby Sizik » Sat May 20, 2017 1:46 pm UTC

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)) { ... }
gmalivuk wrote:
King Author wrote:If space (rather, distance) is an illusion, it'd be possible for one meta-me to experience both body's sensory inputs.
Yes. And if wishes were horses, wishing wells would fill up very quickly with drowned horses.

Tub
Posts: 311
Joined: Wed Jul 27, 2011 3:13 pm UTC

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

Postby Tub » Sun May 21, 2017 12:09 am UTC

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.

User avatar
Soupspoon
You have done something you shouldn't. Or are about to.
Posts: 2480
Joined: Thu Jan 28, 2016 7:00 pm UTC
Location: 53-1

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

Postby Soupspoon » Sun May 21, 2017 1:54 am UTC

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) …

User avatar
Xanthir
My HERO!!!
Posts: 5215
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

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

Postby Xanthir » Mon May 22, 2017 1:18 am UTC

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.)
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

User avatar
PM 2Ring
Posts: 3619
Joined: Mon Jan 26, 2009 3:19 pm UTC
Location: Mid north coast, NSW, Australia

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

Postby PM 2Ring » Mon May 22, 2017 9:58 am UTC


User avatar
Bloopy
Posts: 164
Joined: Wed May 04, 2011 9:16 am UTC
Location: New Zealand

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

Postby Bloopy » Fri Jul 14, 2017 6:11 pm UTC

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.

User avatar
Arancaytar
Posts: 1642
Joined: Thu Mar 15, 2007 12:54 am UTC
Location: 52.44°N, 13.55°E
Contact:

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

Postby Arancaytar » Sun Jul 23, 2017 1:00 am UTC

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.
"You cannot dual-wield the sharks. One is enough." -Our DM.
Image

User avatar
Thesh
Made to Fuck Dinosaurs
Posts: 5497
Joined: Tue Jan 12, 2010 1:55 am UTC
Location: Colorado

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

Postby Thesh » Fri Aug 04, 2017 5:20 pm UTC

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.
Honesty replaced by greed, they gave us the reason to fight and bleed
They try to torch our faith and hope, spit at our presence and detest our goals

User avatar
Xanthir
My HERO!!!
Posts: 5215
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

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

Postby Xanthir » Mon Aug 07, 2017 8:13 pm UTC

No, you get the problem even if you throw away the concept of "truthy/falsey", if the accidental assignment was of a boolean value.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

User avatar
chridd
Has a vermicelli title
Posts: 763
Joined: Tue Aug 19, 2008 10:07 am UTC
Location: ...Earth, I guess?
Contact:

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

Postby chridd » Tue Aug 08, 2017 8:32 pm UTC

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).
~ chri d. d. /tʃɹɪ.di.di/ (Phonotactics, schmphonotactics) · they (for now, at least) · Forum game scores
mittfh wrote:I wish this post was very quotable...
flicky1991 wrote:In both cases the quote is "I'm being quoted too much!"

User avatar
Xanthir
My HERO!!!
Posts: 5215
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

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

Postby Xanthir » Tue Aug 08, 2017 10:24 pm UTC

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.)
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

Demki
Posts: 193
Joined: Fri Nov 30, 2012 9:29 pm UTC

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

Postby Demki » Tue Aug 08, 2017 10:42 pm UTC

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.

EvanED
Posts: 4324
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

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

Postby EvanED » Tue Aug 08, 2017 11:04 pm UTC

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)).

User avatar
Xanthir
My HERO!!!
Posts: 5215
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

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

Postby Xanthir » Tue Aug 08, 2017 11:22 pm UTC

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.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

Sandor
Posts: 172
Joined: Sat Feb 13, 2010 8:25 am UTC

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

Postby Sandor » Wed Aug 09, 2017 11:07 am UTC

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.

speising
Posts: 2068
Joined: Mon Sep 03, 2012 4:54 pm UTC
Location: wien

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

Postby speising » Wed Aug 09, 2017 2:53 pm UTC

2 much typing

Derek
Posts: 2149
Joined: Wed Aug 18, 2010 4:15 am UTC

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

Postby Derek » Wed Aug 30, 2017 7:40 am UTC

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())

User avatar
SpitValve
Not a mod.
Posts: 5124
Joined: Tue Sep 26, 2006 9:51 am UTC
Location: Lower pork village

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

Postby SpitValve » Wed Sep 27, 2017 9:16 am UTC

I think the `for` version feels less tricksy and reads cleaner.

User avatar
hotaru
Posts: 1021
Joined: Fri Apr 13, 2007 6:54 pm UTC

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

Postby hotaru » Thu Sep 28, 2017 9:08 pm UTC

SpitValve wrote:I think the `for` version feels less tricksy and reads cleaner.

unnecessary duplication of code might "feel less tricksy", but it certainly doesn't read cleaner to me.

Code: Select all

factorial product enumFromTo 1
isPrime n 
factorial (1) `mod== 1


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 11 guests