Re:A Defer Mechanism for C
by ziml77 on Monday December 14, 2020 @09:33AM
(#25417964)
Non-obvious need to call defer was what made me stop trying out Go. When I was making HTTP requests there was no Close() method on the response so it seemed like it wasn't needed. But later I found out that there is a Close() method on the response's Body member that needs to be called (only one code sample in the docs even showed that).
RAII is the best for ensuring that things get cleaned up even if it does lead to more boilerplate to add the pattern to things. But even .NET's IDisposable feels better than defer. It's established practice to implement it if your class contains something that must be disposed. And it's easy for tools to check if you haven't disposed of something that implements IDisposable.
All that said, I find defer to be better than nothing. In C, the best I can do for cleanup is having all the cleanup functions called at the end with labels at the various points I need to jump to.
RAII is the best for ensuring that things get cleaned up even if it does lead to more boilerplate to add the pattern to things. But even .NET's IDisposable feels better than defer. It's established practice to implement it if your class contains something that must be disposed. And it's easy for tools to check if you haven't disposed of something that implements IDisposable.
All that said, I find defer to be better than nothing. In C, the best I can do for cleanup is having all the cleanup functions called at the end with labels at the various points I need to jump to.