User:Cjoev/Type safety intro

In computer science, type safety is a property attributed to some, but not all, programming languages. The term is defined differently by different communities who use it — in particular, the formal type-theoretic definition is considerably stronger than what is understood by most programmers — but most uses have in common the notion of employing a type system to prevent certain forms of erroneous or undesirable program behavior (called type errors). This enforcement can be static, catching potential errors at compile time, or dynamic, associating type information with values at run time and consulting them as needed to detect imminent errors, or a combination of both.

The behaviors classified as type errors by any given programming language are generally those that result from attempts to perform on some value (or values) an operation that is not appropriate to its type (or their types). Which of these notions is more fundamental is to a certain extent a matter of opinion: some language designers and programmers take the view that any operation not leading to program crashes, security flaws or other obvious failures is legitimate and should not be considered an error, while others prefer to classify any contravention of the programmer's intent (as communicated via typing annotations) to be erroneous and deserving of the label "unsafe". In the context of static type systems, type safety usually involves (among other things) a guarantee that the eventual value of any expression will be a legitimate member of that expression's static type (the precise requirement is more subtle than this — see, for example, subtype and polymorphism for complications).

Type safety is closely linked to so-called memory safety. To see why, assume for purposes of discussion that a certain implementation of a certain language has some type, say $$t$$, such that there exists some sequence of bits (of the appropriate length) that is not a legitimate member of $$t$$. (All but the most degenerate type systems satisfy this criterion.) If that language is memory-unsafe to the extent of allowing data to be copied from unallocated or uninitialized memory into a variable of type $$t$$, then it is not type safe, because such an operation might assign a non-$$t$$ value to that variable. Conversely, if the language is type unsafe to the extent of allowing an arbitrary integer to be used as a pointer, then it is clearly not memory safe.

In most statically-typed languages, type safety is strictly stronger than memory safety because type systems enforce the proper use of abstract data types defined by programmers even when this is not strictly necessary for memory safety or for the prevention of any kind of catastrophic failure.