Hacker News new | past | comments | ask | show | jobs | submit login

I do it in C code instinctively; it's very useful for instrumentation, debugging, and resource management in straight C to have a single return point. When I get too far to the right, that's a signal that it's time to further decompose my functions; that signal is also useful, which is another thing that keeps me doing it.

But that style doesn't make much sense in Golang. It makes even less sense in Ruby and Python, which have structured exception handling; if you're coming from Pythonistan, the idea of nesting conditions is probably entirely alien.




I agree, having a single return point makes debugging that much easier.

Back at Microsoft, the following pattern was used quite extensively in the OS group:

  int someFunc() {

    DWORD error = ERROR_SUCCESS; 

    error = foo();
    if (error != ERROR_SUCCESS) {
      goto Clean0;
    }

    error = bar();
    if (error != ERROR_SUCCESS) {
      goto Clean0;
    }
    
      ....

    Clean0:
    return error;
  }


This style is used in the linux kernel as well; there can be multiple resources acquired that sometimes need to be released in reverse order, so there are often multiple labels that you can goto, depending on how much stuff you have to unwind before you return.


do you know of any languages that have a sort of inverted switch statement to clean up a list of if statements like this?

something like:

    invswitch err !=nil {
    case 'err := binary.Write(w, binary.LittleEndian, int32(len(g.Name)))': return err
    case _, err = w.Write([]byte(g.Name)): return err
    case err = binary.Write(w, binary.LittleEndian, g.Age): return err
    default: return binary.Write(w, binary.LittleEndian, g.FurColor)
    }


Yes, CPS is essentially that and available in any modern language, or can be emuated by setcontext(2)/getcontext(2). However, it can become a mess very quickly.

Another option is monadic style, which will pass error checking along. I believe it will work well for this example, and can be implemented in Go, most likely (I don't know Go, bur it seems so).

Of course, the real problem with this code is that it is not decomposed properly. Nested error checking is the first sign of it, as somebody else already rightfully noted in the thread.


I think you'd probably need generics to implement monadic chaining in Go.


This is similar to what Haskell do-notation provides.




Consider applying for YC's W25 batch! Applications are open till Nov 12.

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

Search: