Tidy First?
henrikwarne.com
henrikwarne.com
It still amazes me how they can believe that putting all the guards in tens of nested ifs can be saner than a few extra returns at the top.
And don't get me started on those that goto is bad but it's ok to put everything inside a do while (0) they can break out of and clean up at the end.
Sorry for the off-topic rambling, tidying is like "clean" code, everyone has their own definition and sometimes changing code for the sake of making it tidy is more dangerous than just changing the behaviour, especially if it was already tidy by some other people standard.
One specific case I have in mind I think it came from the company mostly hiring fresh graduates and seniors indoctrinating them with their blind and badly aged structured programming rules.
People didn't understand that, too vague, hard to enforce. Someone else decided to make it clearer, "try to avoid multiple returns inside a function".
Then someone else comes and decides to tidy up the coding style document, put it in imperative form: "All functions should have a single return statement".
Give it a couple of years, people forgot why the advice was there in the first place and now they just blindly apply an insane rule, teach that to new hires and enforce it in reviews. All functions now look like big arrows and every once in a while the max line length rule has to be relaxed a little to allow for all those levels of indent.
Maybe that's how it entered MISRA-C in the first place.
But your "return" should also have all deallocations performed! Also if you open communications to some external devices which tend to be notoriously stateful, you need to bring them back to a usable state by either completing commands sent so far, or resetting them, or whatever is needed.
If there is nothing analogous to "defer" statements or "finally" clauses, you will be in a world of pain if you sprinkle return statements without paying attention to all details.
Thus I can see a point of such a rule being in MISRA-C or something like it. Guess it's better to enforce an easily checkable rule (prone to birthing monsters) than educate all people properly.
A recommendation likely lifted from one of these sources.
MISRA 2012, Rule 15.5: "Only one exit point should be defined in a function.", advisory - https://www.ibm.com/docs/en/rtr/9.0.0?topic=review-code-misr...
HN users cordenr and bfrog say it was dropped in MISRA 2023: https://news.ycombinator.com/item?id=38680587 and https://news.ycombinator.com/item?id=38704631 . Both in a recent thread on MISRA 2023 at https://news.ycombinator.com/item?id=38674158 .
FWIW, HN user FirmwareBurner in that thread links to the "Embedded System development Coding Reference guide" version 3.0 (2018) from the Software Reliability Enhancement Center, Japan at https://www.ipa.go.jp/publish/qv6pgp00000011mh-att/000065271... which says
M3.1.5:
A function shall end with one return statement.
A return statement to return in the middle of processing shall
be written only in case of recovery from abnormality.Also, that's great news to hear in case I ever want to go back to the automotive industry. :)
You could flex some language lawyering to define "abnormality"...
Here is the only relevant example I found:
p = X_MALLOC(sizeof(*p) * NUM);
if (p == NULL) {
return (MEM_NOTHING);
}
...
X_FREE(p);
return (OK);
It's clearly abnormal.Something like a:
if (get_size(obj) == 0) {
return empty_case;
}
... do more complicated code here ...
return result;
does not feel "abnormal", which are things you likely want to log, given: Logs should be output not only when an abnormal condition
is detected, but also at the timing of, such as, data
communication with an external system.> Guard clause – exit a function early if certain conditions are not met. This makes the rest of the function easier to write (no nested if-statements).
If you have:
if(!isUserPort(strPort)) return;
You're gaining knowledge about input, and then immediately throwing it away (assuming the 'happy' path.)Later when you use strPort, do you check it again? If you pass it to another function, do you check it there too?
"Parse, don't validate" is the name that's been given to the following:
case parsePort strPort of
NotAPort -> ...
RootPort port -> ...
UserPort port -> ...
It's more nested, but now you can pass your UserPort around and not check it too many or too few times.Unless your parsePort returns a specialized type which then can be enforced by the compiler, and all your other APIs use the specialized representation, it's sort of "six of one, half a dozen of the other" situation because if you're throwing your strPort around, you'll be parsing it again and again and again.
And I can achieve what you are showing me just the same by putting my guard clause up the stack, closer to the main program or whatever.
Not all data is so clear cut, your guard clause may be guarding against a numeric struct member whose value is out of range for this one function to operate.
Which is why I usually have a few different wrenches for each size of nut I may encounter. Not dunking on your approach, let a hundred flowers bloom and all that.
That's blasphemy. There is only one true clean code and that is what Uncle Bob is preaching himself.
I meet them everywhere. It's just obvious how strong culture is.
If I have a function that needs a group of guards like that but local style guides demand a single exit point, I start a boolean like “AllHunkyDory” that gets set false where a return would be. Then you can keep the less nested structure and just wrap the main body in “if(AllHunkyDory){}”.
It is probably a touch less efficient, that variable is going to take up a register at least throughout the checks, but a fiunction with piles of guard clauses is hopefully not in a tight loop anyway so that is unlikely to matter.
(let/cc ret
(when (= y 0) (ret nil)
(/ x y)) #lang racket
(define (division x y)
(let/cc return
(when (= y 0) (return null))
(/ x y)))On the other hand, if you have ten early returns your function should most likely be split into smaller functions anyway. The advantage of sticking to structured programming is that it becomes obvious when it's time to do so.
Another advantage of pure structured programming (which implies a single exit point) is that you can easily add post-conditions to your functions, i.e. assertions which must hold true before the execution returns to the caller.
DEBUG("%s (%s) -> %d", __func__, str_arg, ret);
return ret;
Single return doesn't necessarily mean nested ifs; it can be linear. bool success = true;
if (condition(arg1)) {
success = try_that(arg2);
}
if (success && condition2(arg3)) {
success = other_thing(arg2);
}
...
return success;
Resource acquisition: widget_t *w = widget_create(arg);
gadget_t *g = w ? gadget_create(w, arg2) : 0;
char *gncopy = g ? strdup(gadget_name(g));
if (gncopy) {
// we must have g and w */
}
Early returns can cause bugs; they can be premature. The coder though that if a certain condition is true, none of the other cases matter. And may be that was true, but now some of the cases (perhaps new ones) do matter. Someone wrote code to handle them, but didn't notice it's not reached because of that early return.Early returns can definitely cause bugs, but here we're talking about basic sanity checks and argument validation, not about program logic. Their purpose is if any of those checks fail we are in a very bad state and there's no point on entering the function at all.
[1] https://newsletter.pragmaticengineer.com/p/dead-code-getting...
Another, even better reason to do this is to prevent the declared object ever being in an invalid (e.g., undefined or null) state. If it's born in a valid state, and every method call leaves it in a valid state, it's harder for things to go wrong.
In the C++ world this approach is encouraged, finding its highest form as RAII: the convention of designing classes to be declared as objects (not references to them), with constructors that leave them fully formed, and destructors that silently and automatically clean them up (thanks to deterministic destructor calls -- one of the best decisions made by the language designers.)
Sadly Java prefers the "bean" convention of new-ing up a "blank" object and then calling setAbc(), ..., setXyz() on it. I hope every time you create an object, you remember to call set...() for every field! Including when you add a new field later!
The 'never and invalid state' pattern has one downside: there always seem to be exceptions in business logic and models so it's very hard to require things to be there 100% of the time. I've seen a system being built over a few years that started with valid objects/hard requirements that were partly removed when business needs and exceptions to the rule became more clear. Those changes caused bugs due to code not handling the null/doesn't exist case. Handling that from the start would have been a lot less work.
Keep the declarations, ditch the statements.
Well that sounds like a loaded footgun.
I’d understand one pile not as just throw everything in one function but thoughtfully arrange code with surgical precision into purposeful blocks with no noise or distractions. I.e. it’s as much about getting rid of crap as it is about concentrating the line of execution.
Bringing in the logic into one place then enabled me to eliminate dead code, redundancy and pinpoint bugs that were hidden deep inside helpers but could only be recognized as bugs in the context of the rest of the algorithm.
Sometimes veritable forest of helpers reduces to a single short, clear function.
I have to caveat this though:
> Therefore, reducing coupling will reduce the cost of change.
This seems like unwise advice. People are going to read it as "coupling = bad" and then try to eliminate coupling even between components that are still coupled, through things like dynamic typing, queues and so on. This only reduces the appearance of coupling.
For example say you have an API endpoint that is supposed to perform some action in another service. A lot of people would "decouple" them by having the endpoint place a request in some shared Kafka/MQTT queue or a file or whatever, and then the other service can poll that. Tada! Decoupled! Much better than a direct RPC call right?
Except they still depend on each other - you've just made the coupling less robust, so it can easily break when you make a mistake refactoring.
In my opinion this depends on the use case. If one service has a strong dependency to a different service, it may be a case of "distributed monolith" and they should consider if the functionality should be moved to the original service instead.
If two services need to communicate with each other, I don't see how a message queue makes the coupling less robust. What is the difference between sending a message or making a http call? You still have a coupling between the two services.
Message queues used right can actually increase operational robustness in my opinion. By placing a message on a queue you get a lot of functionality for free.
- You distribute the load automatically so that the risk of overloading a single instance is reduced
- You can limit the ingestion flow, so that services only process the data at a rate that they can handle - If a service fails or shuts down, the message remains on the queue for the next instance to retry. You get a lot of retry logic for "free".
- You can easily monitor and scale resources based on the processing rate of the queue itself. Some queues can be allowed to grow large during peek hours, because they can be processed during off hours, while others may require scaling up the service capacity to cover a minimum latency requirement.
Misuse of message queues may of course lead to distributed monoliths and add a lot of complexity in understanding how data flows within the system. This is not something specific for queues and it's the same for direct HTTP calls. As all things, we need to use the right tool for the right purpose.
Actually, one of my pet peeves are internal web hooks. Web hooks are good at notifying an external partner compared to the alternatives, but the complexity is too great to justify its use for internal services as well. Just use a message queue instead for your own services.
And it is essentially your point.
[1] https://news.ycombinator.com/item?id=38944611 -- https://newsletter.pragmaticengineer.com/p/dead-code-getting...
Newsletter if anyone wants to subscribe https://tidyfirst.substack.com/
I'm sure many other senior programmers have similar thoughts.
I’m about halfway thru, can’t comment on the last third which is different and offers a newish mental model.
tldr: Good but expensive for the content amount. Should be $15 IMO.
Probably the best compliment one can make of such a book.
Common sense tends to be lacking when it comes to coding practices, and books about it don't really help. Instead, they tend to go with practices that are completely detached from reality. Also, things that require unreasonable effort, so that if you don't do it because you are too neurotypical for that, then "you are doing it wrong" and if it doesn't work then it is not the author's fault.
And even if it common sense in that that's what every experienced programmer is already doing, then, still great. First because not every programmer is an experienced programmer, obviously. And even if you are, seeing it writing helps with consolidation.
So really, you are getting me very interested right now.
Someone more freshly baked could probably get a real nice head start with the advice in the book.