Typing
Why?
Type System verifies programmers’ expectation.
Concepts
- Variance
- Invariance, covariant, and contra-variant for generic types.
- In Go this is also referred to as “in type” and “out type”.
- An in type/read-only type (for function parameter) should be covariant. An out type/write-only type (for return value) should be contra-variant. Otherwise it should be invariant.
Flavors of Type System
Safe/Unsafe
- Unsafe = Some operations violate basic structure of program. There are undefined behavior.
- Safe = Every possible operation has a defined behavior.
- Behaviors
- Illegal Operations (defined)
- Unpredictable
- Total chaos
Static/Dynamic
- Static Typing: Type information is only accessed/used at compile time.
- Dynamic Typing
- Type information is stored along with the values.
CMPinstruction is used to type check at runtime.- Allows user-defined types. Using a type table.
- Particularly useful for pulling heterogenous data.
- Gradual Typing: allowing some variables to be type-checked at compile time.
Explicit/Implicit
- Explicit - Programmer states expectations.
- Implicit - Compiler infers the type.
Incompatibilities
- Disallow
- Convert argument(s) to another type
- Bitwise copy (almost always wrong)
- Interpret the value in a useful way (e.g. Perl, copy vector to scalar means length.)
Nominal/Duck/Goose
- Nominal typing, adopted by C++, Java, C#, and annotated Python
- Duck typing, adopted by Smalltalk, Python, JavaScript, Ruby. Objects have types, variables (including parameters) are untyped. The operations supported is what matters.
- Nominal typing checks explicit inheritance, duck typing dynamically checks by invoking the operation, goose typing dynamically checks name of the methods/attribtues.