by ragnese · 5y ago · 0 comments
It's become a meme in my office that I'm the guy constantly bitching about how stupid our languages are. This week I was back on my soap box about the fact that almost zero mainstream (statically typed) programming languages can even let you write down that you want a non-empty string. In some languages you can implement your own class/type that wraps around the built-in string type, but most of the time you are now introducing memory and CPU overhead, can't use your type with other APIs that expect strings, etc. So nobody does that. But ask yourself this: how often have you ever written a function that requested a string as input and actually wanted an empty string? How many times did you not even think about what would happen if someone DID pass an empty string?
Same goes for positive and non-negative numbers. How many times did you write "int" when you actually only wanted a positive number? If I have to type "if x <= 0 throw FooException" as the first line of one more function, I'm going to scream. (A lot of languages do have unsigned ints, to be fair. But some still don't, or their unsigned ints are almost useless.)
People make all kinds of Stockholm Syndrome-y excuses for it ("validate inputs at the edges is all you need"), but the truth is that (most of) our languages are so deficient for expressing really basic ideas.
Thank goodness there are some languages that do try to make it possible to write "newtypes" and try to make concurrency safer. Now if we could just get everyone to adopt those in less than a decade, maybe we'd be able to get to the next generation after that, and then maybe we'll have good programming languages before I die.
Sorry that turned into a rant... :/
You really are asking for a type that is "valid data." Commendable, but not a static property of data. As a fun example, what is a valid email address? Once established as valid, how long will it stay that way? If invalid, how long until it can become valid?
Do I think better typing can be a boon? Absolutely! Can it also be a burden? Absolutely!
Why not indeed? See my other comment https://news.ycombinator.com/item?id=28214776 about how to create such types.
And it isn't like this isn't done often. Take the lowly format string in c languages. With the requirement that the format string has to be static, it is common to fail builds if you give it a bad format string or supply the wrong number of arguments.
Wouldn't you love the compiler giving an error when you write something that could result in illegal state? (Business rule violations for example) This is where such types shine. https://fsharpforfunandprofit.com/posts/designing-with-types...
I'm not asking for someone to supply these things in the standard library of $FOOLANG. I'm saying that very few languages offer the tools to define such things without it being very cumbersome and often incurring significant runtime overhead.
I know it's possible to do better because I've read up a bit on Ada. I've used Rust and written my own "newtypes" with the Deref "trick". I've toyed with Haskell.
So, yeah, please let me define a "PrimeInt" type!
#2 You don't want to write a validator.
#3 Presumably you want to instantiate values of that type with user given input.
I don't think the three requirements make sense at all.
If you're willing to drop #3 you can always use some sort of enum-ish thing.
I want the "validator" to be the constructor of a type (or a refinement mechanism, etc).
Then every function in my code base can have a clear contract via its type signature. What good is a function that says it accepts a string and returns a string if it actually just explodes when given some strings? That's not the same thing as returning a string...
I want to do three-ish things:
1. Make my function's type signature be correct. It is NOT correct to say that you accept an "int" but actually crash if you're given `0`.
2. Push bug catching to compile time instead of runtime. Calling a validation function inside a function is a runtime check. In the meantime I can write 100 calls to a function that I know will cause a crash and the compiler will say nothing.
3. Push type requirements to the callers of functions. Everyone preaches "validate at the edges", but if your function signatures had very precise types, that would happen "automatically." Your code won't compile unless you pipe the correct types all the way from the top function call down to the bottom one.
My argument for why not, is that I don't think it pays off for most uses. You will wind up putting a ton of logic into the types, but then you have to do a ton of logic to correctly serialize into the types you have.
Do I think there are times/places this could pay off? I'd hope/expect so. But where the data hits the wire is likely not where you can set many of these constraints such that your type system can really help with them.
There must be a term for this phenomenon. My original reply that sparked this thread could be tl;dr as "I get frustrated with most programming languages. People at work know me as the guy that always complains about programming languages. One example of that is that I recently complained about most languages making it hard to statically guarantee that an input string is non-empty."
But then I get painted as "dying on a hill" for non-empty strings. It was one example, and it's not even the most important complaint I have about current programming languages. It was just one that came up this week at work because we literally had to deal with a bug from a REST API of a big company because THEY sent an empty string in a JSON payload that isn't supposed to be empty. Their code obviously missed a check somewhere and instead of sending a 404 response, they sent a bad payload (according to their own docs).
> My argument for why not, is that I don't think it pays off for most uses. You will wind up putting a ton of logic into the types, but then you have to do a ton of logic to correctly serialize into the types you have. > > Do I think there are times/places this could pay off? I'd hope/expect so. But where the data hits the wire is likely not where you can set many of these constraints such that your type system can really help with them.
This is hard to debate because we're speaking in very abstract terms. Obviously different domains will have different needs, etc.
So, unfortunately, I'm not sure I follow your argument for "why not". But here's my argument for "why". A lot of times, when we design software, it ends up working in "layers". Some function calls some other function calls some other function, etc.
If that "bottom" function requires something like a non-empty string (maybe that function is going to print a mailing label and it would be ridiculous to waste printer time on a blank label), you have two options: compile time enforcement or runtime enforcement.
In my experience, the majority of the time, "we" choose runtime enforcement, even in statically typed languages. What does runtime enforcement look like? Usually it's one of two things: you throw an exception or you return some kind of failure value.
If you throw an exception, it bubbles all the way up and your top level main loop has to catch it and understand how to handle it. That somewhat implies that your top level has to know everything that could go wrong at any layer of your code.
In addition, you now have a dilemma. You know that if you pass an empty-string through, that you'll eventually hit the function that requires a non-empty string. So you have two sub-options for this option. You can validate at the top level and pass it only if it's valid, or you can pass everything through and potentially do a lot of computational work before hitting the failing function and throwing away all that work. Most people choose to validate at the top level. So, you're validating at the top level anyway, and you're possibly validating in TWO places (the function doesn't know who might call it)- not DRY.
Other issues with the (unchecked) exception approach: It ALSO means that the type signature on your bottom-layer function is LYING. It "said" that you could pass it a string and it would return Whatever. It was wrong. You passed a string and instead of returning a Whatever, it started unwinding the stack for you. That's not static typing. Callers of this function can't trust its type signature to be complete. Instead they now have to read documentation (hopefully you wrote some). But if they already have to read documentation to understand what your function accepts and returns, why did we bother write the types at all? Just use Python or JavaScript and don't put types on anything. You just have to read the docs to know how to call it and the types will never get in the way.
The other runtime option is that your function might return a value that indicates failure. Some languages have "Result" or "Try" types. But if you do that, then the function that calls that bottom function has to handle the return value. There's a good chance that the "second layer" function can't really handle the failure, so it ALSO has to return a failure value. Etc, etc, until every function in the call chain has altered its return type to indicate that it may fail. Then your top level loop inspects the return value and handles the failure. I include Java-style checked exceptions in this category and not in the above "exception" category.
This return-failure-value approach pollutes all layers of your code even worse than if you just had a NonEmptyString type! Instead of the top level inspecting the bubbled up failure value after doing a bunch of computation, it could have just tried creating a NonEmptyString type from the input. If it failed, then the top-level handles the failure same as before, but didn't waste a bunch of CPU and clock time doing computations before hitting the failure. Furthermore, it's very DRY because the validation logic is in the type itself, either in some kind of type refinement mechanism, or in a factory function, etc.
Furthermore, the NonEmptyString type approach gives you more compile-time safety from bugs. If you try to call that bottom function with a maybe-empty-string, it won't compile. In the other cases, you'll only find out at runtime, even though you KNOW ahead of time that it's illegal to do so. I hope your tests cover everything.
I know what you’re trying to get at, but that’s just a category error. It’s a misuse of the term valid in this context. For example my mail archive contains many emails from valid addresses for which there happens to be no currently active mail box end point. They’re still valid data though. The fact that people sometimes use th s term valid to mean something completely different is just an unfortunate linguistic accident, but its a mistake to think it’s meaningful.
You mean something that roughly matches this obvious regex:
\A(?:[a-z0-9!#$%&'*+/=?^_‘{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_‘{|}~-]+)*
| "(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]
| \\[\x01-\x09\x0b\x0c\x0e-\x7f])*")
@ (?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
| \[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:
(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]
| \\[\x01-\x09\x0b\x0c\x0e-\x7f])+)
\])\z
[ Source: https://www.regular-expressions.info/email.html ]That somehow doesn't look "easy" on my eyes. I'm not sure the parent's comment was serous.
Amusingly, this distinction constantly annoys me with contact managers. I don't want to change my friend's phone number to the new one. I want to mark the old one as no longer active, and add the new one. Similar for deceased family.
Back to the point, you seem to want null punning for the empty string. But you still need to check for validity of the value when it is not empty. What does that really gain you?
Those are not mathematical entities in the same way as are the sets W (whole numbers) or N (natural numbers, indices). It is reasonable to specify your domain closely, otherwise you end up with sqlite.
"Why not a type for datetimes or complex numbers?" would be a better question, as those are different kinds of things but not quite so frequently used in programming.
It seems like you're trying to use SQLite as an example of something you don't want to end up with. This seems backwards so it weakens your argument. SQLite is one of the most widely deployed, reliable, broadly applicable and all round useful pieces of software ever written.
Same for other sets like "not-primes", or the odd numbers.
Sets can be nicely approximated with types. (Some people say even that types correspond directly to sets).
You can validate a primitive like an int based on it's own state alone.
And then there is validating it is a valid int, but is it valid to use it somewhere? 7642468 is a valid int, but is it a valid address?
That is, the primitives are unlikely to be your concern in programming. Handy tools, but not your problem domain.
Enumerations come to mind.
CL-USER> (defun non-empty-string-p (string)
(and (stringp string)
(plusp (length string))))
NON-EMPTY-STRING-P
CL-USER> (deftype non-empty-string ()
`(satisfies non-empty-string-p))
NON-EMPTY-STRING
CL-USER> (typep "" 'non-empty-string)
NIL
CL-USER> (typep " " 'non-empty-string)
TToday D will fulfill your dreams!
struct MyString {
private string s = "error";
alias s this;
this(string s) {
assert(s.length);
this.s = s;
}
}
void main() {
MyString ms = "hello";
test(ms);
MyString mserror = ""; // runtime assert fail
}
void test(string s) { }If D had unlimited access to C code at CTFE then maybe you could implement refinement types at compile time as a library but for now you are stuck with what Walter has posted. I implemented a sketch of the API for this ages ago but the actual type checking had to be done at module load time because was of aforementioned (justified) restrictions to CTFE
Dependant types are a whole other monster.
Scala to the rescue:
https://github.com/fthomas/refined
And a new one:
https://github.com/Iltotore/iron/
The latter will be zero overhead once a compiler ticket is closed.
Both solutions will yield compile time checks where possible, and fall back to runtime checks when the data isn't statically known.
I worked on a Scala once several years ago and I really didn't "get it". The more I use Kotlin, the more I wish it were Scala.
If you are disappointed in programming tools, you didn't see hardware design tools yet.
To be fair, I do it quite often. Most of the strings I deal with in my code are coming from user input, and most of them are optional. They are usually just passed to/from a database. If the string has some internal meaning (like ULSs or file paths), it usually gets wrapped in an object anyway.
If you're processing some formal language or network protocol, that's another story.
> I've written a number of RESTy/CRUDy APIs and I can't count the number of "check that username isn't empty" checks I've written over the years.
Paraphrasing: "I've written the same kind of method over and over throughout my career and have been unable to (or made no attempt to) abstract it away." I love strong type systems, but it doesn't sound like the type system is your problem here. The problem is that you're constantly re-implementing the same business logic.
Well, of course you should be able to declare something non-null. What do I look like, someone who likes Java? :p My point wasn't that I WANT to use null instead of an empty collection/string, it was that our languages give us multiple mechanisms by which we can pass in "nothing" for strings/collections, but they give us zero ways to ask for a non-empty string/collection. That's super frustrating! Yes, of course "null" and "empty set" are technically and semantically different. But they're close enough that you could actually deal with having only non-empty strings + nulls and be able to mostly express what you want. That's not the case if I actually want a non-empty string in many of today's languages. Not if I want it to be usable with other APIs and the standard libraries, that is.
> Paraphrasing: "I've written the same kind of method over and over throughout my career and have been unable to (or made no attempt to) abstract it away." I love strong type systems, but it doesn't sound like the type system is your problem here. The problem is that you're constantly re-implementing the same business logic.
Eh, no. I haven't worked in the same language or on the same project for my whole career. So, yeah, I've noticed that I'm pretty much always either defining a bunch of boilerplate types up front or I regret not doing it when a 0 hits the database because someone wasn't careful with their math or had an off-by-one error.
Maybe I should publish a book a la Gang of Four and call it "Static Type Patterns". ;)
So, yeah. Believe it or not, I HAVE implemented stuff like PositiveInt and NonEmptyString a bunch of times in a bunch of languages. And it's better than not having it, but it still sucks because in several of those languages, it means that I have all kinds of noise converting to and from, e.g., the native string type. And that's because most of the above languages have no concept of "newtypes" and have no intention of letting programmers define or refine "primitives".
It's not really about "business logic". It's about "I know how to describe the shape of this data, but my statically typed language won't let me."
But you do it only once, thereafter you have hopefully some "Username" type of object which is guarantied to contain a valid username.
But, the reason I'm bitching about it is because, in most languages, you then cannot use your Username type in place of a "native" string, where some third-party or standard library function just expects a string. So now you have to convert back and forth.
And if this is a language like pre-record Java, fucking forget it. Define the class, implement equals(), implement hashCode(), write a getter for the wrapped string so that you can pass its guts to functions that expect strings, write the constructor. Speaking of the constructor, do you let the constructor throw an exception? Do you make the constructor private and write a factory function? Does that factory throw an exception or return a failure value? Checked exception or unchecked exception?
Now do that everywhere that you want a "newtype".
Is it possible? Absolutely. I've done it. Is the amount of effort for such a simple concept reasonable? No.
And my other point is that I actually want a non-empty string MUCH more often than I want a potentially-empty string.
I think that programmers are especially prone to just internalizing bullshit and papercuts. We like "solving puzzles" and we're pretty smart and adaptable. So when we encounter something that's actually kind of insane, but we eventually figure out a workaround, we completely forget that it was ever insane in the first place (see: Gang of Four patterns).
subtracting one from zero and getting max_uint can be its own brand of fucking horribly awful.
having the language itself throw in that circumstance can also be exactly what you don't want.
type Byte is unsigned 2**3;
This will permit any value in the range [0,7] and when you exceed it (in either direction) it will wrap around (the desired action if you choose this type). In contrast: type Byte is range 0..7;
Will give you a runtime error when you exceed the bounds by trying to increase beyond 7 or decrease below 0. Having this choice is nice, you get to decide the semantics for your system.It has a lot of positive features going for it, but it is verbose. That verbosity is a major distraction for people who can't handle it, they want their very short keywords or, better, no keywords just symbols. Curly braces are somehow better than begin/end even though begin/end really aren't hard to type. Ada shines, particularly, in the long tail of system maintenance, not in the writing (arguable: the type system certainly helps a lot in the writing, the syntax doesn't). So I press for it where it belongs, and don't where it doesn't. But when someone laments the state of type systems, I point it out.
procedure Foo is
type Byte is range 0..7;
T : Byte := 0;
begin
T := Byte - 1;
end Foo;
(Not that that's useful code, but a basic example.) That shouldn't make it past the SPARK/Ada system to compilation. Now change it to this: function Foo(T : Byte) return Byte is
begin
return T + 1;
end Foo;
and SPARK/Ada should warn (been a bit, but should also fail to compile) that this could cause overflow.Agreed. Silent wrap-around on overflow is also a really terrible idea.
> having the language itself throw in that circumstance can also be exactly what you don't want.
Then you have to check before you do it. Or call a special overflowing function. The default should absolutely be a crash. That wouldn't even really be anything new: what happens when you divide by zero in most languages? Index an array with an index > length? Should the array index just wrap around and give you the element at length % index?
(i < 0) || (i > n)
when you can just simplify it to (i > n)
after verifying that n < max_uint?Unless it isn’t a monad and I still haven’t understood those?
Statically typed languages give you u8/i8 types of numbers.
Maybe having a non empty string, or non empty list, type is useful now and then, but in practice, just have your code work just as well on both empty and non empty values, and you're good to go.
I'm pretty happy with the languages we have today overall (Kotlin and Rust at the top, but C#, Swift, and Java get an honorable mention).
As another commenter said, some statically typed languages give you unsigned numbers. Maybe most of them do. But definitely not some of the most popular ones. And out of the ones that do, they are often really unhelpful.
C's unsigned numbers and implicit conversions are full of foot-guns.
Java basically doesn't have unsigned ints. It does kind of have this weird unsigned arithmetic API over signed ints, but it's really awkward and still bug-prone to use.
Kotlin's unsigned numbers API is very poor. Very. Kotlin does not give a crap if I write: `Int.MIN_VALUE.toUInt()`, so it's perfectly happy to just pretend a negative number is an unsigned number. Not to mention that unsigned number types are implemented as inline/value classes which don't even actually work correctly in the current version of the language (just go look at the bug tracker- I literally can't use value classes in my project because I've encountered multiple DIFFERENT runtime crash bugs since 1.5 was released). It, like Java and C, etc, is perfectly happy to wrap around on arithmetic overflow, which means that if you didn't guess your types correctly, you're going to end up with invalid data in your database or whatever.
Rust and Swift have good unsigned number APIs.
Notice also that I didn't say anything about non-empty collections. Yes, I absolutely want non-empty collection types, but that is no where NEAR as important and useful as non-empty strings, even though they might seem conceptually similar. I'm willing to assert, like the bold internet-man I am, that you and all of the rest of us almost NEVER actually want an empty string for anything. I never want to store a user with an empty name, I never want to write a file with an empty file name, I never want to try to connect to a URL made from an empty host name, etc, etc, etc. It is very often perfectly acceptable to have empty collections, though. It's also very frequent that you DO want a non-empty collection, which is why we should have both.
We don't even need empty strings (or collections, really) if we have null.
You say you like Kotlin and Rust and I work with both of them extensively. I can point out a great many shortcomings of Kotlin in particular. I used to be enamored with it, but the more I use it, the more shortcomings, edge cases, bugs, and limitations I run into. Rust is pretty great, but even that has some real issues- especially around how leaky the trait abstraction is. But at least Rust's excuse is that it's a low-level-ish systems language. It's these "app languages" that irritate me the most.
This feels exactly backwards to me: I almost always want my sequence-like types to have a well-defined zero-length element, and I almost never want to allow a NULL value for a variable. NULL is so much worse than [] or ''. Think about concat(). When the trivial members of a type support most of the same behaviors as the nontrivial ones, that makes error checking so much easier.
I'm just exasperated that most of these modern, statically typed languages, give us TWO ways to write "nothing" (null and empty) and ZERO ways to write "must have something".
You COULD, theoretically, write a concat() that takes multiple, nullable, non-empty strings and returns a nullable non-empty string. Of course that's not ideal and would be horribly unergonomic. But you COULD do it. But how do you write a concat() that statically guarantees that if any of its arguments are non-empty that its output will be non-empty? You pretty much don't.
In such languages (e.g. Kotlin), null is perfectly safe to use whenever you need to represent an absent value.
I'd read that newsletter.
For example, what if I don't like data class's stupid copy() method? How do I opt out? You can't.
Value classes can't be used as varargs, can't implement an interface by delegating to the wrapped value. (Forgetting the fact that they're just buggy as all hell and I keep getting runtime crashes from them being overly aggressively optimized away)
And it, of course, inherits a ton of badness from Java. Like the crappy type-erased generics, lack of type classes, etc. It chose to just use Java's standard collection types and encourage copies instead of using persistent collections by default. It hides the mutability under "read only" interfaces, but that's not at all concurrency-safe. Map is not a Collection or an Iterable, which is dumb. Map<K, V>'s type parameters are also allowed to be nullable types, which means that Map.getOrElse{} is actually wrong in the standard library.
Since Kotlin chose nullable types instead of Option<T>, you can't express "nested" emptiness. This means that the Map API is janky if you need to store nullable types. Map.get returns null if there was no value stored, but what if the value stored IS null? Then you have to call Map.contains(key), which means you have to hash the key twice to reliably pull out values.
There's just a lot of papercuts.