Wednesday, November 26, 2014

Type Safety

Type safety is closely linked to memory safety, a restriction on the ability to copy arbitrary bit patterns from one memory location to another. For instance, in an implementation of a language that has some type t, such that some sequence of bits (of the appropriate length) does not represent a legitimate member of t, if that language allows data to be copied 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 not memory-safe.
Java
The Java language is designed to enforce type safety. Anything in Java happens inside an object and each object is an instance of a class.

To implement the type safety enforcement, each object, before usage, needs to be allocated. Java allows usage of primitive types but only inside properly allocated objects.

Sometimes a part of the type safety is implemented indirectly: e.g. the class BigDecimal represents a floating point number of arbitrary precision, but handles only numbers that can be expressed with a finite representation. The operation BigDecimal.divide() calculates a new object as the division of two numbers expressed as BigDecimal.

In this case if the division has no finite representation, as when one computes e.g. 1/3=0.33333..., the divide() method can rise an exception if no rounding mode is defined for the operation. Hence the library, rather than the language, guarantees that the object respects the contract implicit in the class definition.

C++
Some features of C++ that promote more type-safe code:

    The new operator returns a pointer of type based on operand, whereas malloc returns a void pointer.
    C++ code can use virtual functions and templates to achieve polymorphism without void pointers.
    Preprocessor constants (without type) can be rewritten as const variables (typed).
    Preprocessor macro functions (without type) can be rewritten as inline functions (typed). The flexibility of accepting and returning different types can still be obtained by function overloading.
    Safer casting operators, such as dynamic_cast that performs run-time type checking.

No comments:

Post a Comment