Which one is better defer (multiple defers)?

defer func(){
    A()
    B()
}()

OR

defer B()
defer A()

I’d say it depends on which one seems clearer in the context. If they are two separate things, two separate may be better.

in, err := os.Open(...)
// ...
defer in.Close()

out, err := os.Create(...)
// ...
defer out.Close() // generally, don't defer closes on writable files. Example only.

If it’s just two things that should happen together, together is fine. For example, here the write deadline is just about making the close work:

conn, err := net.DialTLS(...)
// ...
defer func() {
    conn.SetWriteDeadline(time.Now().Add(time.Second))
    conn.Close()
}()

But like @NobbZ says below (I ninja edited, sorry :)) this is really because the defer is still about the same resource.

2 Likes

I prefer to have a single defer releasing a resource as soon as possible after claiming the resource.

I never do a defer that is unrelated to a resource.

So from my point of view version 1 is unlikely to happen for me.

On writable files, you can defer close, but always remember to call Flush() as last thing and check the error returned there.

Yeah, I shouldn’t have brought it up at all and it was a bad example that I just typed out… Certainly it’s possible to use defer close on writable files. But equally the error handling should usually be better. If you were writing a file and it failed somewhere, closing it is not the primary concern. Should we leave a half written file around? Likely it should be cleaned up somehow. If we were doing it correctly we were probably writing to a temp file that we intended to rename to the final destination name. If so the close isn’t the last thing to happen (the rename will be), and we shouldn’t defer it, and so on.

Like I said, bad example, reality is more complicated. :slight_smile:

2 Likes

I would say have multiple defer() function calls. You will have room to handle failures from Defer func1() in defer func2().
In the below code:
defer func(){
A()
B()
}()
Any err in A() and B() you need handle.

Below code had more flexibility. Easier to handle, code readability.
defer B()
defer A()

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.