4 ms·
The blog post that introduced it (https://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html https://commandcenter.blogspot.com/2014/
by Someone 4y ago
The blog post that introduced it (https://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html https://commandcenter.blogspot.com/2014/01/self-referential-...) mentions
func DoSomethingVerbosely(foo *Foo, verbosity int) {
prev := foo.Option(pkg.Verbosity(verbosity))
defer foo.Option(prev)
// ... do some stuff with foo under high verbosity.
}
but I don’t see why that’s better than
func DoSomethingVerbosely(foo *Foo, verbosity int) {
prev := foo.setVerbosity(verbosity))
defer foo.setVerbosity(prev)
// ... do some stuff with foo under high verbosity.
}
It also mentions that it allows you to “set lots of options in a given call”. That, you could sort of accomplish by having the setProperty methods return the changed object, thus allowing chaining (e.g. foo.setVerbosity(v).setDryRun(true)).
This allows both that defer and setting lots of options in a single call.
Given the limited features of go, it’s a nice hack, but I don’t like it. To me, it doesn’t feel like it fits the philosophy of go.
- djur 4y agoYour chaining example and the defer example can't both work together, since they both rely on different return types for SetVerbosity.