logoalt Hacker News

Someonetoday at 1:12 PM2 repliesview on HN

I think Swift’s defer (https://docs.swift.org/swift-book/documentation/the-swift-pr...) was inspired by/copied from go (https://go.dev/tour/flowcontrol/12), but they may have taken it from an even earlier language that I’m not aware of.

Defer has two advantages over try…finally: firstly, it doesn’t introduce a nesting level.

Secondly, if you write

       foo
       defer revert_foo
, when scanning the code, it’s easier to verify that you didn’t forget the revert_foo part than when there are many lines between foo and the finally block that calls revert_foo.

A disadvantage is that defer breaks the “statements are logically executed in source code order” convention. I think that’s more than worth it, though.


Replies

kibwentoday at 4:37 PM

I'll disagree here. I'd much rather have a Python-style context manager, even if it introduces a level of indentation, rather than have the sort of munged-up control flow that `defer` introduces.

show 1 reply
mojubatoday at 1:28 PM

Yeah, it's especially handy in UI code where you can have asynchronous operations but want to have a clear start/end indication in the UI:

    busy = true
    Task {
        defer { busy = false }
        // do async stuff, possibly throwing exceptions and whatnot
    }