Strong/weak typing describes the ease of mixing variables of different types in expressions. Strong typing does not imply static typing just as weak typing does not mean dynamic typing.
To put it simply, if a programming language tries to interpret an expression containing variables of varying types at runtime (e.g. adding an int to a string), then it is most probably weakly-typed however if it throws an error; then it is strongly-typed.
Strongly-typed languages do not try to deduce programmer intent when they come across expressions containing varying types; they throw errors and do not do any implicit type coercion.
#python two = "2"; #String four = two + 2; #KA-BOOM!!! #TypeError: cannot concatenate 'str' and 'int' objects
This should not be confused with dynamic typing where a variable’s type can change; the issue here is trying to use a type (string) where another type (int) is expected. To make the above example pass, the string needs to be cast into an int.
#python two = "2" #String four = int(two) + 2; #four is now 4
Weakly-typed languages allow you to mix types in expressions: the compiler will not throw an error, rather it’ll try to deduce your intentions. This can lead to really weird bugs that occur one thousand miles away from the origin.
The compiler implicitly assumed that you were concatenating strings (the expression is ambiguous: it involves adding a String to a Number) and ‘helped’ to make this happen. However, the code will probably blow up because “five” is not 5.
What you should know
Strongly-typed languages do type-checking on variables at runtime and only allow legal operations for that variable type to be carried out whereas weakly-typed languages try to inteprete (understand/guess) the user intentions.
Strong typing does not imply static typing, it means that a language will not automatically coerce a variable into another type to make expressions valid. Weak typing however means that the type of a variable can be changed at run time based on its context in expressions.
In general, the ease of detecting programming errors decreases as you go from one to four in the list below. Due to the implicit conversions in dynamic weakly-typed languages, bugs might be caused by seemingly innocent code.
1. Static & strongly-typed: Haskell
2. Static & weakly-typed: C
3. Dynamic & strongly-typed: Ruby, Python
In conclusion, it is good to know that the strong/weak delineation however is blurred and not clearly-cut. To avoid ambiguity and confusion, it’s better to describe languages with respect to type safety and that should insha Allaah be the next post in this series. Hang on…
Did you enjoy this post? Read the first post.