This can be a useful pattern - though I’ve never seen it used for this usecase. A similar one is templating languages (like Jinja) where you need to wrap strings if you want to send HTML to your templates with them being escaped on render.
We use something similar where we have a BadNumber class in our code (python). Any operation with another number will also create a BadNumber. It allows us to make sure that these tainted numbers are always obvious.
Re:The Rule of 2
by heavenlyblue on Sunday August 11, 2019 @01:26PM
(#20669237)
You could use an import hook in python, then create a whitelist of APIs that will be mapped to UnsafeString and then will receive SafeString as an argument.
How about implementing it as an access modifier like "trusted" and enforce that only values from other trusted members can be assigned to a trusted member?
Re:The Rule of 2
by staticassertion on Saturday August 10, 2019 @02:42PM
(#20663801)
I think this is just refinement types. You wouldn't so much ban the stdlib as need to wrap it.
Just have two separate types, e.g. UnsafeString and regular String, and some kind of `convert` function that takes a validation function as an argument. You'd get compile-time checking that way.
People don't tend to use such things in practice though, and you would also have to ban a portion of most language's standard libraries to enforce it in practice (because they already return regular strings for inputs).