The compiler is your best friend

(blog.daniel-beskin.com)

71 points | by based2 3 hours ago

11 comments

  • LegionMammal978 1 hour ago
    > How many times did you leave a comment on some branch of code stating "this CANNOT happen" and thrown an exception? Did you ever find yourself surprised when eventually it did happen? I know I did, since then I at least add some logs even if I think I'm sure that it really cannot happen.

    I'm not sure what the author expects the program to do when there's an internal logic error that has no known cause and no definite recovery path. Further down the article, the author suggests bubbling up the error with a result type, but you can only bubble it up so far before you have to get rid of it one way or another. Unless you bubble everything all the way to the top, but then you've just reinvented unchecked exceptions.

    At some level, the simplest thing to do is to give up and crash if things are no longer sane. After all, there's no guarantee that 'unreachable' recovery paths won't introduce further bugs or vulnerabilities. Logging can typically be done just fine within a top-level exception handler or panic handler in many languages.

    • skydhash 1 hour ago
      A comment "this CANNOT happen" has no value on itself. Unless you've formally verified the code (including its dependencies) and have the proof linked, such comments may as well be wishes and prayers.

      Yes, sometimes, the compiler or the hardware have bugs that violate the premises you're operating on, but that's rare. But most non pure algorithms (side effects and external systems) have documented failure cases.

      • JohnFen 1 hour ago
        > A comment "this CANNOT happen" has no value on itself.

        I think it does have some value: it makes clear an assumption the programmer made. I always appreciate it when I encounter comments that clarify assumptions made.

        • addaon 1 hour ago
          But if you spell that `assert(false)` instead of as a comment, the intent is equally clear, but the behavior when you're wrong is well-defined.
          • JohnFen 1 hour ago
            I agree that including that assert along with the comment is much better. But the comment alone is better than nothing, so isn't without value.
          • zffr 2 minutes ago
            At least on iOS, asserts become no-ops on release builds
          • eterm 1 hour ago
            Better yet, `assert(false, message)`, with the message what you would have written in the comment.
            • addaon 1 hour ago
              `assert(false)` is pronounced "this can never happen." It's reasonable to add a comment with /why/ this can never happen, but if that's all the comment would have said, a message adds no value.
              • eterm 1 hour ago
                Oh I agree, literally `assert(false, "This cannot happen")` is useless, but ensuring message is always there encourages something more like, `assert(false, "This implies the Foo is Barred, but we have the Qux to make sure it never is")`.

                Ensuring a message encourages people to state the assumptions that are violated, rather than just asserting that their assumptions (which?) don't hold.

        • skydhash 1 hour ago
          Such comments rot so rapidly that they're an antipattern. Such assumptions are dangerous and I would point it out in a PR.
          • LegionMammal978 1 hour ago
            Do you not make such a tacit assumption every time you index into an array (which in almost all languages throws an exception on bounds failure)? You always have to make assumptions that things stay consistent from one statement to the next, at least locally. Unless you use formal verification, but hardly anyone has the time and resources for that.
            • skydhash 1 hour ago
              If such an error happens, that would be a compiler bug. Why? Because I usually do checks against the length of the array or have it done as part of the standard functions like `map`. I don't write such assumptions unless I'm really sure about the statements, and even then I don't.
              • LegionMammal978 4 minutes ago
                > or have it done as part of the standard functions like `map`.

                Which are all well and good when they are applicable, which is not always 100% of the time.

                > Because I usually do checks against the length of the array

                And what do you have your code do if such "checks" fail? Throw an assertion error? Which is my whole point. Or does calling them "checks" instead of "assumptions" magically make them less brittle from surrounding code changes?

              • tosapple 16 minutes ago
                How does one defend against cosmic rays?

                Keep two copies or three like RAID?

                Edit: ECC ram helps for sure, but what else?

      • threethirtytwo 19 minutes ago
        False it has value. It’s actually even better to log it or throw an exception. print(“this cannot happen.”)

        If you see it you immediately know the class of error is purely a logic error the programmer made a programming mistake. Logging it makes it explicit your program has a logic bug.

        What if you didn’t log it? Then at runtime you will have to deduce the error from symptoms. The log tells you explicitly what the error is.

      • AnimalMuppet 47 minutes ago
        Worse: You may created the proof. You may have linked to the proof. But if anyone has touched any of the code involved since then, it still has no value unless someone has re-done the proof and linked that. (Worse, it has negative value, because it can mislead.)
        • skydhash 36 minutes ago
          Not really. A quick git blame (or alternative) will give you the required information about the validity of such proof.
          • dullcrisp 0 minutes ago
            You must have some git plugin I haven’t heard about.
    • the__alchemist 1 hour ago
      This is what rust's `unreachable()!` is for... and I feel hubris whenever I use it.
    • GabrielBRAA 1 hour ago
      Heh, recently I had to fix a bug in some code that had one of these comments. Feels like a sign of bad code or laziness. Why make a path that should not happen? I can get it when it's on some while loop that should find something to return, but on a if else sequence it feels really wrong.
      • kccqzy 15 minutes ago
        Strong disagree about laziness. If the dev is lazy they will not make a path for it. When they are not lazy they actually make a path and write a comment explaining why they think this is unreachable. Taking the time to write a comment is not a sign of laziness. It’s the complete opposite. You can debate whether the comment is detailed enough to convey why the dev thinks it’s unreachable, but it’s infinitely better than no comment and leaving the unreachability in their head.
  • doug_durham 9 minutes ago
    Typing is great, presuming that the developer did a thorough job of defining their type system. If they get the model wrong, or it is incomplete then you aren't really gaining much out of a strictly typed language. Every change is a fight. You are likely to hack the model to make the code compile. There is a reason that Rust is most successful at low level code. This is where the models are concrete and simple to create. As you move up the stack, complexity increases and the ability to create a coherent model goes beyond human abilities. That's why coding isn't math or religion. Different languages and approaches for different domains.
  • onionisafruit 8 minutes ago
    He mentions this is from a podcast. Anybody know what podcast? It seems like something I might like to listen to.
  • kridsdale1 1 hour ago
    I really like modern Swift. It makes a lot of what this author is complaining about, impossible.

    The worst file I ever inherited to work on was the ObjC class for Instagram’s User Profile page. It looked like it’d been written by a JavaScript fan. There were no types in the whole file, everything was an ‘id’ (aka void*) and there were ‘isKindOfClass’ and null checks all over the place. I wanted to quit when I saw it. (I soon did).

    • glenjamin 9 minutes ago
      Any advice on how to learn modern Swift?

      When I tried to do learn some to put together a little app, every search result for my questions was for a quick blog seemingly aimed at iOS devs who didn’t want to learn and just wanted to copy-paste the answer - usually in the form of an extension method

  • ZebusJesus 1 minute ago
    This was a great breakdown and very well written. I think you made one of the better arguments for rust Ive read on the internet but you also made sure to acknowledge that large code bases are just a different beast all together. Personally I will say that AI has made making code proofs or "formal verification" more accessible. Actually writing a proof for your code or code verification is very hard to do for most programmers which is why it is not done by most programmers, but AI is making it accessible and with formal verification of code you prevent so many problems. It will be interesting to see where programming and compliers go when "formal verification" becomes normal.
  • smj-edison 19 minutes ago
    > Rust makes it possible to safely manage memory without using a garbage collector, probably one of the biggest pain points of using low-level languages like C and C++. It boils down to the fact that many of the common memory issues that we can experience, things like dangling pointers, double freeing memory, and data races, all stem from the same thing: uncontrolled sharing of mutable state.

    Minor nit: this should be mutable state and lifetimes. I worked with Rust for two years before recently working with Zig, and I have to say opt-in explicit lifetimes without XOR mutability requirements would be a nice combo.

  • barishnamazov 48 minutes ago
    The "lies" described here are essentially the definition of weakly typed programming, even in statically typed languages.

    Functional languages like ML/Haskell/Lisp dialects has no lies built in for decades, and it's good to see the mainstream programming (Java, TS, C++, etc.) to catch up as well.

    There are also cute benefits of having strong schemas for your API as well -- for example, that endpoint becomes an MCP for LLMs automatically.

  • moth-fuzz 29 minutes ago
    I'm not a fan of the recent trend in software development, started by the OOP craze but in the modern day largely driven by Rust advocates, of noun-based programming, where type hierarchies are the primary interface between the programmer and the code, rather than the data or the instructions. It's just so... dogmatic. Inexpressive. It ultimately feels to me like a barrier between intention and reality, another abstraction. The type system is the program, rather than the program being the program. But speaking of dogma, the author's insistence that not abiding by this noun-based programming model is a form of 'lying' is quite the accusatory stretch of language... but I digress at the notion that I might just be a hit dog hollering.
  • skydhash 1 hour ago
    The whole article gives a generated vibe, but I did want to point out this particular snippet

    > The compiler is always angry. It's always yelling at us for no good reason. It's only happy when we surrender to it and do what it tells us to do. Why do we agree to such an abusive relationship?

    Programming languages are a formal notation for the execution steps of a computing machine. A formal system is always built around rules and not following the rules is an error, in this case a malformed statement/expression. It's like writing: afjdla lkwcn oqbcn. Yes, they are characters, but they're not english words.

    Apart from the syntax, which is a formal system on its own, the compiler may have additional rules (like a type system). And you can add even more rules with a static analysis tool (linter). Even though there may be false positives, failing one of those usually means that what you wrote is meaningless in some way. It may run, but it can have unexpected behavior.

    Natural language have a lot of tolerance for ambiguous statements (which people may not be aware of if they share the same metaphor set). But a computer has none. You either follow the rules or you do not and have an error.

    • xnorswap 1 hour ago
      I also don't like that phrasing. It's like complaining of guard-rails while running around erratically.

      The guard rails aren't abusing you, they're helping you. They aren't "angry", they're just constraints.

      • scubbo 49 minutes ago
        Right, and I suspect that was the author's intent - to evoke a sympathetic frustration that newer programmers might feel, and then to point out how the frustration is ill-aimed.
  • mock-possum 1 hour ago
    Hello baader meinhoff my old friend - while I’m familiar with the convention, I was just introduced formally to the phrase “functional core, imperative shell” the other day, and now here it is again.

    “Learn to stop worrying and love the bomb” was definitely a process I had to go through moving from JavaScript to Typescript, but I do mostly agree with the author here wrt convention. Some things, like using type names as additional levels of context - UserUUID and ItemUUID each alias UUID, which in turn is just an alias for String - have occurred to me naturally, even.

  • pointbob 14 minutes ago
    [dead]