5 ms·
> Programmers with lots of hours of maintaining code eventually evolve to return early, [..] I agree with all your other points and I‘d even agree if you wrote
by weinzierl 9y ago
> Programmers with lots of hours of maintaining code eventually evolve to return early, [..]
I agree with all your other points and I‘d even agree if you wrote return early makes code more readable but not that it‘s something experienced programmers do.
Programming is still - to some degree - resource management.
Inexperienced devs often miss that fact, because they are focused on memory management and believe they can rely on the garbage collector for clean-up. In real projects you quickly end up managing file descriptors, sockets, handles, GUI resources, etc.
Early return is terrible for that, because your coding style starts to depend on the kind of resource to manage.
That‘s why the more experienced folks end up writing single exit point code sooner or later.
EDIT: I‘m not arguing that early return and proper resource management are incompatible, just that most experienced programmers have often been burnt enought to avoid it.
- monocasa 9y agoThat's one of the reasons I love RAII; all resources, memory and otherwise, are treated the same.
- jasonmaydie 9y agoit's not just about in app resources. This could also affect external resources.. like not cleaning up temporary files because a future maintainer returned early and left some critical data behind.
- klmr 9y agoRAII can handle such resources, and good use of RAII does handle such resources. Languages without time-deterministic GC even tend to add extra language constructs to aid this, such as `using` in C# and Java (7?) with its new `try` block.
- weinzierl 9y agoThat‘s what I was thinking when writing my edit. The somewhat ironic thing is that C++ people could use early exits safely, but often don’t, while Java folks typically write early exit code when they really shouldn’t.
- jstimpfle 9y agoDownside is, now your cleanup code is spilled all over the codebase. And where it's implemented it lacks often the necessary context (from the location of use). So, it's often wrong or incomplete, or suffers from the type-for-single-usage syndrome. Yes, RAII works for the casual std::vector, but it's not a maintainable solution for general resources.
- monocasa 9y agoIt's right next to the create code, not 'spilled all over the codebase'. And if you really want different behavior on destruction (which is _really_ rare IMO), you can pass a destruction strategy at object construction. If you don't know how you want to destroy something when you construct it, you need to take a step back and reexamine your architecture.
- Too 9y agoTrue, for those who don't agree, read about rule-of-zero for some expansions on this. If you have to write the same type of clean up code in multiple destructors you are doing it wrong, wrap that resource in a class that has the responsibility of managing that type of resource and forget about the destructors elsewhere.
- jstimpfle 9y agoAnd the create code is spilled over the codebase, just as well :-). It's not where actual work is done. This approach of encapsulating functionality in a class may work in some instances such as std::vector but more often than not it's just a lot of (typical OOP) boilerplate for things that you do only once in a codebase anyway. Giving one-off things a type and a name and decoupling them from normal control flow (ripping them out of context) makes things just harder to understand. Better just make them global data, maybe even define the initialization/cleanup routines for that global data in-line with the rest of the control flow.
- monocasa 9y agoI mean, having global resource managers is orthogonal to generating the events that cause resource destruction. And you're not 'ripping them out of context's, since the guard objects are still there where you would be doing the resource management manually. EDIT: and I was the lead for a high availability C++ RTOS. I know that not all patterns fit for writing quality, available code. This fits remarkably well though. Even though we were totally async and didn't rely on the stack for context lifetimes.
- 3pt14159 9y agoOh common. This might be true for a very specific type of codebase, but it isn't true for programming in general. If I'm coding a library of standard statistical functions I'm exiting early. If I'm coding a Rails webapp I'm exiting early. If I'm coding a shell script, even one used on tens of thousands of servers, I'm exiting early. The resource almost all programmers are managing is the resource of human time. Human time to code the project, human time to review the code, human time to alter the code after the fact, human time to port the code to different environments. If you're writing code to run AI at Google then fine, you're managing resources at a level where performance starts to hit limits that warrant a style change, but generally speaking you know that ahead of time and you choose tools to handle a project of the right scope, but generally speaking exiting early isn't impacting your code performance. Big O mistakes are.
- bottled_poe 9y agoI guess I would agree with the concept of managing “human time”, but I believe you are focusing on the wrong human. The developer will certainly spend a lot of time writing and maintaining a code base, but that’s minuscule compared to the time spent by the end user. What software design principles will save the user the most “human time”?
- weinzierl 9y agoCleaning up resources after use is not a question of performance, it is a question of correctness.
- 9y ago
- recursive 9y agoI have doubts about whether "real" projects generally have these kinds of concerns. But even if they do, you can clean them up in a `finally`, or your language's equivalent.
- monocasa 9y agoMost languages with try/catch/finally don't have checked exceptions, so handling resource management in the those schemes is really brittle.
- klmr 9y ago`finally`/RAII doesn’t depend on checked exceptions. It always runs (short of something that aborts the program without unwinding the call stack; and in those cases single-exit won’t save you).
- monocasa 9y agoMixing finally and RAII into the same category doesn't really make sense here. And I'm not saying that finally depends on checked exceptions, I'm saying that pattern is very brittle. You change lower code to throw a new exception, and you change the above code to catch it like you're supposed to, but now the middle code has no idea that there's this new exception and leaks resources. So you end up either having brittle code who's correctness depends on implicit choices of the code around it, or you're wrapping pretty much all function bodies with try-catch-finally-rethrow.
- Chris_Newton 9y agoI find it a good rule of thumb to allocate and deallocate a resource at the same level in my design, and to maintain any associated handle at that level as well. I have encountered few situations where this didn’t work well, and almost all of them arose because an external module introduced some form of unavoidable asymmetry at its interface. If you’re able to follow that pattern then safe handling of unusual control flows tends to follow naturally. You just adopt whatever mechanism your language provides for scheduling the code to clean up and release resources at the same time as you allocate those resources. Almost all mainstream languages at a higher level than C provide a suitable mechanism today: RAII, some variation of `with` or `using` block, try-finally, Lispy macros, Haskelly monad infrastructure, etc. That way, the only places you need to write any extra logic are the layers where you allocate/deallocate and possibly lower layers that manage side effects on those resources in the unusual case that they require a specific form of recovery beyond the default behaviour in the event of aborting early. Hopefully if you do have to work at low level like C or assembly language and you’re using forms of control flow that could bypass clean-up logic then you already have at least some coding standards established for how to manage resources safely as well.
- drawkbox 9y ago> starts to depend on the kind of resource to manage. Exactly, simple but not too simple. If the condition does not need to return early or can't, you don't. > quickly end up managing file descriptors, sockets, handles, GUI resources In some of the cases you describe you wouldn't return early or depending on the need, but if you can you should to minimize work. Some examples: file descriptors you'd return early if the file does not exist, sockets you'd return if dropped or compromised and you have performed cleanup, handles if null, gui resources can be lots of things but if you were doing something where you needed to cleanup you can cleanup and return. In C# for instance you might wrap some of that in a using such as files, sockets, streams etc. Most of your examples you might already be in the meat of the return early flow and usually there is still a return at the very end but in/after the meat. Returning early isn't saying do a dirty break or asserting out, you don't return early before cleaning up if you are within some resource.
- jstimpfle 9y agoWrong. You need to exit before resource allocations :-). And in general if you allocate resources in most functions you're doing it wrong. Need global resource managers. Stack variables should only very rarely be resource owners.
- monocasa 9y agoRAII works just as well for heap allocated objects as it does for stack allocated ones.
- Too 9y agoSingle exit point is not compatible with exceptions which most GC languages use extensively. Resource management in such environments is done with finally/using/with. Even C has auto cleanup with __cleanup__ attribute in both gcc and clang.
- boomlinde 9y agoI frequently use `goto` in C for this reason. A very common pattern is that I acquire some resources, do something with them, and have a section at the end of the function where I release them in LIFO order. This is labeled so that failure to acquire any resource will jump to a label just before the resources that were acquired before it are freed. Other languages have constructs that obviates this pattern, for example Python has `with` blocks that acquire resources and free them upon leaving the block, and Go has a `defer` statement which adds code to some LIFO structure that always gets executed upon returning.
- christophilus 9y agoIs this true? C# and Go both have a nice way to clean up disposables on early return. I'd imagine most languages are similar these days?