‹ BackHN Continuity

Thread

Rusty thoughts on "Parse, don't validate"

95 points · 47 comments · ingve

  1. Fluorescence · · focus · HN ↗
    Not sure that type is good advice:

        pub struct NonEmpty<T> {
            pub head: T,
            pub tail: Vec<T>,
        }
    
    You'd have to manually implement the traits to support the ergonomics of slices and iteration and costly reallocation if you need to pass ownership as a Vec:

    I'd expect:

        pub struct NonEmpty<T> {
            v: Vec<T>,
        }
    
    The constructor would enforce the invariant and then you'd impl Deref and DerefMut for [T] to gain normal len/is_empty/indexing/iteration, passing as &[T] to other funcs and mutating values (which can't break the invariant).

    To mutate length while preserving the invariant it's dealers choice e.g.

    - add .into_vec() for unwrap/mutate/rewrap

    - add invariant preserving mutators of your choice

    1. Rusky · · focus · HN ↗
      There&#x27;s a whole follow up post about this: <a href="https:&#x2F;&#x2F;lexi-lambda.github.io&#x2F;blog&#x2F;2020&#x2F;11&#x2F;01&#x2F;names-are-not-type-safety&#x2F;" rel="nofollow">https:&#x2F;&#x2F;lexi-lambda.github.io&#x2F;blog&#x2F;2020&#x2F;11&#x2F;01&#x2F;names-are-not-...
      1. Fluorescence · · focus · HN ↗
        Not sure switching between languages makes for a compelling argument:

        &quot;Look how easy it is to accidentally bypass the invariant of a rust newtype by transliterating the data shape into Haskell and deriving a new type&quot;. Uh, ok.

        If comparing the &quot;risk of accident&quot; between a newtype wrapper whose only role is enforcing the the invariant versus manually reimplementing vector and iterator semantics to use a different layout... I&#x27;d say the newtype wins that.

        It would be good advice to keep a newtype that enforces an invariant as a single purpose primitive type. A building block and not a place to add other features.

        There might be times I&#x27;d prefer structural enforcement e.g. something serialisation related. Converting into a non-rust format is what they are doing in their &quot;accident&quot;!

        1. [deleted] · · focus · HN ↗

          [deleted]

Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.