• AstridWipenaugh@lemmy.world
    link
    fedilink
    arrow-up
    2
    ·
    1 year ago

    When you’re interpreting a JSON request payload, how do you tell the difference between a property that’s not set and a property that is set to nothing? I.e. {"key": null} vs. {}. The former would be an instruction to clear the value and the latter is not set.

    • itslilith
      link
      fedilink
      arrow-up
      1
      ·
      1 year ago

      json is one of the old things we now just have to deal with, since JS and by extension json implement a null value. And for parsing arbitrary json data, I currently don’t have a good answer.

      But when parsing a request payload, you usually know what properties to expect, and what types their values should be. Some keys are always present, for example UUIDs or other resource identifiers, and can therefore be directly parsed. But optional keys should be parsed differently, using Option Types. That way, you directly know what data type the field would have as well, if it were present. null in weakly-typed languages is especially bad in that regard, for example if you have something like this:

      {
          "name": "Bob",
          "year": 1989
      }
      

      and both fields are nullable, you would expect them to be different types, but if they are both null, suddenly they’re the same. The absence of a null type forces you to deal with optional values when parsing them, not when trying to do operations with them, which is the problem that null coalescing seeks to simplify.

      I really like what Rust is doing in that regard, with the Option enum, and I know that functional programming languages like haskell have been doing it for a long time with their Maybe monad. I don’t think functional programming is accessible enough to challenge most of the current paradigms, but this is definitely a thing we can learn from them.