4 ms·
You try to parse the received data into a predefined data type, if this fails you are forced by the type system to handle the failure scenario, if it parses cor
by pka 8y ago
You try to parse the received data into a predefined data type, if this fails you are forced by the type system to handle the failure scenario, if it parses correctly you now have a 100% valid data structure you can work with in the rest of your codebase, no defensive checks necessary.
- Kiro 8y agoHow does that work? I thought static typing was only checked when compiling.
- dbattaglia 8y agoImagine some language with the following type and functions: type Person { name: String } function parsePerson(json: String): Person { ... } function usePerson(person: Person) { ... } The compiler will guarantee that usePerson will always get the correct shape of data for it's person variable. The only function you need to worry about is parsePerson, which will generally throw a runtime error if the incoming JSON does not conform to the expected shape. And in most web frameworks, the JSON to type parsing is done for you so once the framework hands you data in the type you are asking for you can expect it to be correct.
- dfgdghdf 8y agoYou write code at the entry point that might fail. Perhaps it returns either structured data or an error. From that point on, you can work only with structured data and the type-system will help you. You might be able to generate a parser from a schema.
- int_19h 8y agoIn most modern languages with static types, types are reified - i.e. actual values have some runtime type associated with them, and it's impossible (or, at least, exceedingly difficult) to create a value that has the wrong representation for its type. In practice, with parsing, this usually means that runtime type metadata is used. Effectively, types become your schema, and you can validate against them as needed.
- ubernostrum 8y agoStatic types can and usually are checked at compile time. Whether the language runtime also uses type checks while running depends entirely on the language and the runtime. IIRC, the JVM (to take an example) more or less throws away a lot of the static type information -- which is often too generic to be useful in guiding optimization -- in favor of runtime profiling, and several of its key optimizations involve inserting runtime type checks.