Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

when to use not (!) with else

 
Sam Hume
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A nitpick reads something along the lines of: Avoid using a not (!) and an else in the same statement...Test for == and swap your if and else blocks.

Now, I'm aware of this rule of thumb, but I've also heard that it's better to put the expected result first and the exception in the else block. So, in the case of checking for failed method I might do something like:



In this case the normal and expected result of my method is to return a non-null result and keep on truckin'.

So my question is: which is easier to read?
1) eliminate the not (!) and swap the if and else blocks
or
2) keep the not (!) and put the expected/normal case first (as I've shown in the example)

And, are there any cases where using not (!) and else together makes sense from a readability standpoint?

Cheers,
Sam
 
M Easter
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with your questioning of the nit-pick.

IMHO, it is best to have the "happy case" in the if block and the "unusual case" in the else... and let the logical expression be whatever it happens to be.
 
paul wheaton
Trailboss
Pie
Posts: 21749
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another way to look at it is that you are getting the off case out of the way up front.

This is a topic that can be at the heart of some mild debate. Kinda like "top down" vs. "bottom up."

Since the camps are generally evenly divided about "do happy path first" vs. "get the odd ducks out of the way first", and everybody can agree on simplifying code ... I think that what your nitpicker is suggesting is generally the best route.

Make no mistake - this is more of a guideline than an absolute. Readability is always king. And there are limitations to the english language.
 
Sam Hume
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since the camps are generally evenly divided... I think that what your nitpicker is suggesting is generally the best route.

No doubt. I followed the nitpicker's guidance assuming there's more wisdom to be found down that path. But this is a nitpick I wanted to explore a little, rather than simply complying and moving on.
 
Marilyn de Queiroz
Sheriff
Posts: 9067
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
pseudocode:
if the methodResult is not null, continueSinceMethodSucceeded.
if the methodResult is not not null, failDueToUnexpectedResult

I think this has the potential to be confusing.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic