3 ms·
Since I do web apps Strings are my bread and butter. If you make UntrustedString a subclass of String (trusted) then you lose type safety. So TrustedString has
by MBCook 1y ago
Since I do web apps Strings are my bread and butter.
If you make UntrustedString a subclass of String (trusted) then you lose type safety. So TrustedString has to be the subclass. Easy enough.
But now string literals are “untrusted”. So you have to do new String(“this is trusted content”) everywhere you need it, which is a pain.
And you can’t add trusted strings. The operator will return a normal String (untrusted) so you have to cast it. Same with any function you call like substring.
So you have to live with that, or make overrides for every single string function that fix the types where necessary.
It’s just really non-ergonomic. I think having it built in would likely make it far better.
- lock1 1y ago> But now string literals are “untrusted”. So you have to do new String(“this is trusted content”) everywhere you need it, which is a pain. Eh? Isn't that the main point of doing all of this? Being explicit on the boundaries but still providing a way to manipulate them like a String? I don't see anything wrong with `new Validated("literal")` (or functional friendly `Validated.of("literal")`). If you intend to create a `Validated`, then create it via constructor / static factory method that enforces necessary validations to create `Validated`. > So you have to live with that, or make overrides for every single string function that fix the types where necessary. Like `Optional<T>` and `Stream<T>`, you could define `Validated::map(Function<? super String,String>)` if you want. With `map()`, you could operate `Validated` with anything that accepts `String` like usual. With that said, I don't recommend using `Validated` in your actual Spring project though, use (OOP) value objects instead. I used value objects quite a lot on my legacy Spring project. It plays nicely with functional-style, cover "validation" stuff, and avoiding primitive obsession. Putting `String` on `UserId` will result in a loud compiler error.