DRY is not really a general programming principle per se. It’s only worth advocating for when it serves a real purpose: avoiding actual errors in the code. Otherwise it is just another layer of textual indirection that people have to think about, and it avoids the many useful and pedagogical reasons to write code that repeats itself.
With that said, there is probably a reason
typeof doesn’t currently exist in rust (or most modern languages) and I’d like to attempt to highlight the reasoning for that. To many of us, it feels archaic and needlessly imperative.
Anyway it all begins with what you think a prgram is. If you think of a program as a syntactic construct that instructs the compiler about what to do, then naturally
typeof makes sense. You’re saying “Hey compiler. I gave you an expression, and I know you’ve got type info on it in your memory banks, so do that lookup and substitute the result for this expression.”
It makes perfect sense if you’re the kind of person who looks at a program as a tree of text and “substitution of one part for another” as a primitive operation.
But if you think of a program as a semantic contruct which upholds invariants and encodes notions of behavior, then it doesn’t make sense. What would instead make sense is to declare your intent to make one expression depend on the type of another, and let the compiler expose the relationship through a language construct. (Rust already does this kind of thing using traits.)
But these differences are not wholly symmetrical, because in the first case, “telling the compiler what to do” makes it really hard to write a compiler. Now you have to think of edge cases like “what if they use
typeof of a captured closure variable on a trait constraint in a generic parameter of a triply nested function definition?” And the answer will either be “let’s forbid that”, so now
typeof doesn’t work everywhere users expect it to, or “well, we better expose every decision the compiler makes to the user so they can construct any software that fits their fancy, despite the fact that we’re going to basically add a whole giant runtime and reflection system to the language to do so.”
I’m fairly certain a modern version of
typeof should look like a declaration-in-a-context so as to not give anybody the impression that it is a fundamental type system primitive that lets people write their own ad-hoc typesystem atop Rust’s expression machinery.