• fristest (unregistered)

    frist

  • gleemonk (unregistered)

    If the rest of the code was solid, I wouldn't care much. Haha, I lied. Even then I would care.

  • fristest (unregistered)

    frist

  • Hanzito (unregistered)

    Dear Lord. If you have a moment, find out who taught Joe how to program, and strike him mercifully with lightning.

  • Krzysztof Słychań (google)

    He should keep trying and enter the International Obfuscated Javascript Coding Contest someday.

  • poniponiponi (unregistered)

    Well, if you're hellbent on never using goto or multiple returns, this is the type of shit you end up with.

    (Sidenote: The fascists who designed Java/Python/etc. who decided goto needed to be abolished at the language level should be shot.)

  • (nodebb)

    Unsurprising. It's PHP.

  • gnasher729 (unregistered)

    This pattern (do ... while (false) with break statements) is what you use in C++ if the compiler refuses to accept goto statements, which happens a lot in C++ due to various reasons. That should give you an indication how often you should see the pattern: Every time that a goto statement would have made sense, but ran into practical problems with the compiler. I think I've used it once.

    (There is the other situation where it is used to wrap macros so that they both syntactically like normal statements, that's very common).

  • Someone (unregistered) in reply to poniponiponi

    Admittedly, python has a lot of flaws. It's not an awful language, I still do all my small little projects with it. But there a lot of "quirks" to it... Capitalising True/False/None, no switch statements, no do while (which I find myself wanting a lot), no block comments... It's a long list.

    And then people crap on about how "beautiful" and "simple" a language it is... without switches and do whiles, nothing is simple.

  • unwesen (unregistered) in reply to poniponiponi

    Well the only sensible use of goto I keep seeing is essentially what other languages provide with finally. I would prefer finally over goto, if available.

  • my name is missing (unregistered)

    Who the hell has time to go onto a conference room with everyone on the team and critique a single short function????

  • unwesen (unregistered) in reply to gnasher729

    Do while false is especially useful with EAGAIN and continue, so basically whenever you do non-blocking I/O. It's not half as weird as the author makes it out to be.

    And using exceptions for anything that is not exceptional is an anti pattern. Null is often much better.

  • Matt (unregistered)

    IIRC the "do { } while(false)" or a similar idiom is used in a ton of Linux kernel macros as a way to produce a multiple-line statement that works like a single-line one.

    Whether macros would have helped Joe or made it worse is an exercise for the reader.

  • Bill (unregistered) in reply to my name is missing

    I assume the "//Code goes here" part was significant enough to justify a full review.

  • Brad Wood (google)

    This reminds me of the handy select construct as it could be used in ye olde Visual Basic. List your preconditions, then do what you need to do:

    Select Case True Not somePrecondition ' some exception Not someOtherPreCondition ' some other exception Case Else ' code goes here End Select

    Addendum 2017-05-01 08:47: Sheesh, why can't newlines in comments just work?

  • I dunno LOL ¯\(°_o)/¯ (unregistered) in reply to gnasher729

    This pattern (do ... while (false) with break statements) is what you use in C++ if a co-worker refuses to accept goto statements, which happens a lot in C++ due to stupid reasons.

    FTFY

    This "single point of exit" shit really is pretty dumb.

    There is one use of this which I consider valid, and that's in C macros to make a macro parse like a single statement no matter where you put it.

  • Troll Spotter (unregistered) in reply to Someone

    Admittedly, python has a lot of flaws. ... no block comments...

    """ eh,

    It's no so bad.

    This text does nothing. """

  • unwesen (unregistered) in reply to Matt

    It's also used for scoping in C++ macros. Though reasonable compilers allow scope blocks, too.

  • unwesen (unregistered) in reply to I dunno LOL ¯\(°_o)/¯

    It's particularly dumb if you follow some kind of contract programming mindset, do a fair bit of parameter checks first, and bail out on errors.

    I once had an employer who demanded both in their guidelines.

  • Bonkey (unregistered) in reply to Hanzito

    mercifully?

  • efinr (unregistered) in reply to unwesen

    And using exceptions for anything that is not exceptional is an anti pattern. Null is often much better.

    well... there obviously was an exceptional case..

    } catch (Exception e) {

  • Herby (unregistered)

    Most of this (and comments) seem to be founded in some "coding rules" that seem to come down from parts above with illogical explanations. I suspect that most of them were to counter a specific example of "bad code" that caused the module/subroutine/procedure to fail in some spectacular way. This empowered some WTF "boss" that has little experience to issue edicts that evolved into the aforementioned "coding rules".

    Of course they make little sense when applied over the wide swath of code produced every year, but (as usual) the justification is that "it would have saved us if...".

    Now (as is said with regular expressions) you have two problems. The actual task at hand, and the work-arounds of the silly rules that are case in stone.

    At least some things (MISRA) have outs of you document them well.

    Lesson for all of us to learn (and hopefully PHBs who think their power comes from the amount of edicts they issue).

    Life goes on.

  • Developer Dude (google)

    Ooookaaaaay....

  • Sole Purpose of VIsit (unregistered)

    Amongst other idiocies (and in general I think Herby wins the thread):

    It's not all that difficult to implement a do-while loop in Python. Test the predicate first, and then use the standard Python while loop.

    I fail to see why either this, or the particular capitalization or nomenclature of True/False/Null, should have any bearing at all on the quality of a language.

    (And for the record, I'm a C++ man.)

  • Fedaykin (unregistered)

    The only correct response to this type of code review and unrelenting argument from a developer is:

    "Thank you for you time and efforts; You're fired."

    The RWTF is that this person was kept around.

    Code should first be correct and clear. Nested if statements and other languages that are used when goto is not available can be very verbose (fugly), but they are clear and can easily be maintained. Mangling an unrelated control structure (a loop) into a total abomination like this is even more fugly in addition to being more difficult to maintain. There is one, and only one reason to accept such a terrible pattern, and that is if there is an imperative to keep the source code as small in size as possible. For example, if for some reason you are using an interpreted language in a networked environment with extremely limited bandwidth.

  • Old Beard (unregistered)

    Sounds like there are a lot of Dot Net developers in here that don't really understand "code", but instead just understand "Microsoft's way".

    Go out into the real world and spend a few years.

  • nb (unregistered) in reply to gnasher729

    Yup. I worked on a firmware codebase that was full of do{ }while(0); code. It's not an antipattern within limited scopes, particularly when the DRCs flag multiple return statements and gotos as errors.

    The DRCs may be WTFfy themselves, but I'm not shocked by the pattern and have used it myself when it makes sense.

    I am a fan of early returns (I know there are haters out there). int status = STATUS_FAIL; at first failure: set status to exact failure condition if known, return status; at end of function: return STATUS_OK;

  • emurphy (unregistered)

    "Ah, but it gets so messy, all the indentation." So move the "Code goes here" block into a second function, ReallyDoSomething() or whatever.

  • emurphy (unregistered)

    Second private function, that is. Damn my laziness in not bothering to log in before posting...

  • Jonathan (unregistered) in reply to Old Beard

    How close minded, behind the times and arrogant you sound. The article's code looks very much like C# code to me, C# code and Java code are practically identical in many regards, so your statement really doesn't make sense.

    I am C# dev myself and there is no "Microsoft way" that I am aware of, there is just doing things in an OO way with proper exception handling strategies and being cognisant enough of its memory management so as avoid memory leaks.

    You may have been thinking of VB, but that language retired a long time ago, anyone still using it and "liking" it is clearly stuck in the past. VB.net is really in essence just VB like syntax for C#, built I guess to try pull the die hard VB people onto modern .NET, but in the MS space, C# is really where it's at these days.

    Standard disclaimer for all languages also applies to C#/Java, use the right tool for the job. with them being GC'ed, high level languages, they will simply never be appropriate for certain kinds of jobs, but they are entirely competent at a wide variety of tasks.

  • Jonathan (unregistered)

    Oh, and in regards to the article's code, assuming it's C#, it is a complete WTF as it is working around an arbitrary and likely self imposed constraint. Any other developer looking at the code would find themselves needlessly wasting time to understand what the inappropriately used control structures are (obtusely) achieving, only to ultimately conclude that the original developer was being a moron.

  • Jeff Grigg (unregistered)

    I would look at all the places that call this method, and all other methods coded in a similar way. Do any of them ignore the returned error message instead of handling it properly? (Most likely, many of them do.) That's The Real WTF: Returning an error indication instead of throwing an exception is an anti-pattern. It's the reason why we have exceptions. Fix that, and most of the rest of this pattern will go away by itself.

    And yes, it's OK for guard clauses to have return statements. Yes, it violates the rules of structured programming. But still, it's a good idea, for good reasons. And most guard clauses should throw exceptions when they fail, anyway.

  • Mick (unregistered)

    Should be while (false) { } then it would run faster!

  • (nodebb)

    Quite frankly I'm more offended by the unconditional exception-swallowing than the do-while-false (even though I have some exception-swallowing in some parts of my code; but I don't put it fucking everywhere).

    The do-while-false with the breaks on failed precondition is more of a symptom than the WTF itself: It's a symptom of WTF-y blind obedience to the "single entry, single exit" mentality. While I agree that "boomerang code" (or however it's called) is a problem, I solve it by, as a rule, excluding precondition checks from the SESE idiom: the idea is that precondition checks are not supposed to allocate resources, therefore they don't need to be included in the nested if blocks.

  • (Kris) (unregistered)

    The only WTF is the application of this pattern to a garbage-collected language. I have used the pattern extensively in C++ code that needed to perform transactional operations, where you go through a sequence of resource allocations, any of which could fail. It's safe and clear, and avoids deeply-nested if() statements. If the resource allocations are acquired using C++'s object-initialisation-is-resource-allocation pattern, the do { } while structure guarantees that every object that had been constructed inside the scope up to the point of the "break;" statement would have their destructors called IN REVERSE ORDER before execution drops out of the "loop". (goto isn't the answer to this problem; object destruction happens when a scope is exited in a controlled manner, and goto isn't a controlled exit - that's why the compiler stops you: it knows when using a goto will fuck up your object destruction.)

    If C++ allowed "break" from a bare scope (i.e., just a pair of braces without a flow-control statement), the do/while(false) wouldn't be needed.

  • Aurioch (unregistered)

    Sooo... what's wrong with simply ANDing (&) all preconditions inside a single if, and running the code if expression is true? Even better, AndAlso (&&) (yes, I love it, same with OrElse) since it skips the check of rest of preconditions the moment one of precondition is false.

  • (nodebb) in reply to Aurioch

    Same problem as in run-on sentences (it's less easy to comprehend), compounded by minor problems such as that if you don't put it on a single line (which will cause you to need to scroll), you find yourself with the condition broken over several lines and some code beautifiers (such as Visual Studio's) don't handle this part well.

  • Aurioch (unregistered) in reply to Medinoc

    That may be so, but I think it really depends on the number of preconditions and the size of expressions of those preconditions. For situations where there's few preconditions And expression could still be readable, especially if those preconditions are already evaluated beforehand.

    And if you have something like 20 preconditions limiting when the code is executed, then I have to ask why is the code designed like that.

  • Chris Paterson (google)

    So you have code review sessions where everyone agrees Joe's code is wrong, and Joe's allowed to overrule all of them and keep doing this garbage. What's the point of the code review process?

  • (nodebb) in reply to (Kris)

    "If C++ allowed "break" from a bare scope (i.e., just a pair of braces without a flow-control statement), the do/while(false) wouldn't be needed."

    It would, because of macros that are called like functions (and consequently have a semi-colon after them in normal use). You need something between the end-brace and the semi-colon (and while(0) is approximately perfect for it, especially as there is nothing else that works) so that you can use the macro before an else...

  • Anon (unregistered)

    Nah. EVIL is throwing a "continue" into a "do {} while(false);".

    Or using labels...

  • Ugh (unregistered) in reply to Aurioch

    This may not be the case here, but in some cases you can't simply && together your conditions. Also, if they're complex enough conditions, it may be more readable (and easier to edit) to have multiple checks instead of one massive one.

  • Paul (unregistered) in reply to my name is missing

    Dear God, please forgive us for trespassing by thinking that the shitty function was worth critiquing.

    Anyway, if You, God Almighty, had a little more time, You would read more carefully and realize that ALL of that dumb fuck functions are structured in the same way.

  • Rainwulf (unregistered)

    Im a pub arduino coder yet this had me saying "what the fuck" out loud.

  • Andrew (unregistered)

    I may be in the minority but I rather like this pattern, but I think it's better used in languages which don't support exceptions (C comes to mind). In a language such as C++ or C#, this probably isn't the best way to go about it since exceptions are being used anyway.

    I used to abhor the use of "goto" as I was taught in school. However, a few years of writing drivers in Linux has relaxed that opinion: proper use of goto's is not evil. What is nice with this pattern is the way it "reads", e.g.:

    int SomeFunction(....) { int retVal = 0; do { if (/something important/ != /found/) { retVal = EINVAL; break; } /* similar checks after doing the work and bail with the right error * when necessary */ } while(0);

     return retVal;
    

    }

    In reality, the same thing is accomplished with judicious use of "goto". Over the years, I've grown to rather like the "return only at the end of the function" because I've been bitten (and been in code reviews where others were bitten) by an innocuous looking conditional which contained a return that went unnoticed and caused grief.

  • Mike (unregistered) in reply to Fedaykin

    What I rarely see in dev comments is talking about code readability and clean code in general. It is an anti-pattern when a coder gets adept in reading entangled obscure "code"×2... they just dont get it, that you have to pay that price every time you glance at it.

  • Mike (unregistered)

    Devs who think this is a good way of breaking down complexity, probably never heard of extract method -> so you can name the beast to tame it.

Leave a comment on “Do While False”

Log In or post as a guest

Replying to comment #:

« Return to Article