Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Any time I write "if err == nil" I write // inverted just to make it stick out. It would be nice if it was handled by the language but just wanted to share a way to at least make it a bit more visible.

    if err == nil { // inverted
        return err
    }


I do something similar. I leave a comment but with a short comment why it’s inverted.

It’s usually pretty obvious why: eg

    if err == nil { 
         // we can exit early because we don’t need to keep retrying
But it at least saves me having to double check the logic of the code each time I reread the code for the first time in a while.


I know diddly/squat about Go, but from similar patterns in aeons past, would "nil == err" work as a way to make it stand out?


Just tried this and it appears to be valid in the compiler, formatter and golangci-lint


https://en.wikipedia.org/wiki/Yoda_conditions

Works especially well in languages that can make assignments in if statements, e.g:

if foo = 42 { }


Thank you, I was unaware of this label. Quite descriptive.


Something slightly more elegant (in my subjective opinion) you could do is write

  if !(err != nil) {


Would be nice if code editors colored it differently so it's easier to see.


return nil

would be clearer, I think. Seems like it's the same but would color differently in my editor.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: