Type safety and type soundness refer to the extent to which a programming language discourages or prevents type errors.
Type safety là mức độ mà một ngôn ngữ lập trình không khuyến khích/không cho phép các lỗi kiểu dữ liệu.
int number = 5;
String text = "hello";
//Error
let result = "5" + 2; //Result = 52
let sum = "5" - 2; //Result = 3
Type safety is not the same as static/dynamic typing or strong/weak typing.
Type safety means that if a data item has type X
and
X
doesn't support operation y
, then a
type-safe language can't perform y(X)
. This can be checked
in different ways:
Consider the following Java code, which can compile but may result in a type error at runtime:
Object obj = "I am a string";
Consumer<String> consumer = (Consumer<String>) obj;
In this example:
obj
is actually a
String
; it only knows that an Object
can be
cast to any type (in this case, Object
is cast to
Consumer<String>
).
obj
is a String
and attempts to cast
String
to Consumer<String>
, resulting
in a type error.
A strongly typed language does not allow implicit changes to data types.
To change a data type, explicit casting or functions are required (e.g.,
str()
in Python).
Note: Python is considered a strongly typed language if we don't
strictly define strong typing, because Python allows operations like
double + int = double
(e.g., 1.0 + 2 = 3.0
).
A weakly typed language allows implicit changes between data types.
For example, JavaScript is a weakly typed language.
Suppose a char variable have 1 byte and a int variable have 4 byte. I want to cast int to char in programming language C.
int number = 300; // In binary: 00000000 00000000 00000001 00101100
char character = (char) number; // Only last byte is keep, 00101100 = 44 = "," in ASCII
printf("%c\n", character); // ","
printf("%d\n", character); // 44