Static vs Dynamic Typing

1 mainIf you are a programmer, you must have heard the terms “static typing” and “dynamic typing” being thrown around a lot. When we talk about programming languages, this is an important feature that tends to significantly affect the programs written in that language. In the spirit of simplicity, I will try to keep this post as code-free as possible. Actually, you don’t have to know any programming language in particular to understand this concept. If you are doing a hobby project or doing something simple, this will not come into picture and it will not affect your code as such. As you build bigger systems, static and dynamic typing will become a big concern. If you are not fully aware of the limitations of a given programming language, you will end up spending a lot of time in code maintenance. So it’s always good to know some of these things. Alright, so what exactly is it about? Does it really matter that much?  

What do you mean by “typing”?

The word “typing” refers to typing on the keyboard. So static typing refers to typing on the keyboard without moving your fingers and dynamic typing is, well, typing dynamically on the keyboard. That could be one possible explanation, don’t you think so? Okay, jokes aside! The word “typing” in our case has nothing to do with the actual keyboard typing. When we talk about “typing” in the world of programming languages, we are referring to the data types and the associated manipulation allowed by that language. The words “static” and “dynamic” refer to two different types of typing, and they are the opposite of each other. Now that we have cleared up the whole “typing” confusion, let’s move forward.

What is static typing?

Static typing is a feature of a given programming language. The programming languages in which we have to declare the variables explicitly before using them are called statically typed languages. Here, you don’t have to define the variables before they’re actually used. C, C++, and Java are good examples of static typed languages. Now wait a minute, can you not cast those variables into other types? Can we still call it a statically typed language? Well, the answer is yes! The thing to note here is that when you cast a variable into another type, it doesn’t get converted. It is just being read differently by assuming that it belongs to another type.

As we discussed earlier, static typing doesn’t mean that we have to define all the variables first. We just need to declare them before using them. Let’s look at the following C++ code:

int a;           // note that we are declaring a variable explicitly
a = 5;           // it’s okay to modify it
cout << a + 5 ;    // it’s okay to use it

Compare the above code fragment to the following:

cout << b + 7 ;

This code will throw an error because we haven’t declared the variable ‘b’ anywhere. C++ doesn’t like that! C++ compiler checks for “types” during compile time and throws an error is something is off.

What is dynamic typing?

Dynamic typing is also a feature of a given programming language, and it’s the opposite of static typing. Dynamic typed programming languages are those in which variables must necessarily be defined before they are used. But the good thing is that these variables need not be declared, and they need not be bound to a particular type. Python is a very good example of a dynamic typed programming language. Consider the following Python code:

x = 23      # directly assigning the value to a variable
print x

Notice how we just directly assigned a value to ‘x’. We didn’t have to declare that ‘x’ is an integer. The Python interpreter will understand it and associate ‘x’ with int. In dynamically typed languages, type checking is done during run-time. What this means is that you can assigning anything to any variable and you will not be caught. This looks so flexible, right? I mean, you can be carefree and do anything you want here. Well, not exactly! We’ll see why this might be a problem soon.

Is this the same as Strong vs Weak Typing?

2 strong vs weakA lot of people tend to use these terms interchangeably. Perhaps one of the reasons for this is that the concept of strong and weak typing is defined very loosely. The concept of static vs dynamic typing is very different from strong vs weak typing. There are no hard and fast rules that can be used to determine whether a given language is strongly or weakly typed. But that doesn’t mean it’s completely open to interpretation. Let’s discuss strong vs weak typing and see if we can understand them.

What is strong typing?

The programming languages in which variables have specific data types are strongly typed. Well, that’s obvious! When are data types not specific? Okay may be that was not all that clear. A better way to put it would be that in strongly typed languages, variables are necessarily bound to a particular data type. For example, Python is strongly typed. Wait a minute, didn’t we just say Python is flexible and we don’t need to follow any rules? Well, be that as it may, the difference between strong and weak typing is a bit more subtle than static vs dynamic typing. Go into the Python shell by typing “python” on your terminal and do the following:

>>> var = 'a'
>>> var + 5
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>>

In this example, var is of ‘str’ type. In the second line, we are trying to add 5 to it. As we know, an int cannot be added to a variable of ‘str’ type. This is shown in the error message thrown by the Python interpreter. This behavior characterizes strongly typed languages. Once you assign a variable to something, it is bound to that type. So even though Python is flexible, it doesn’t allow you to be naughty!

What is weak typing?

Weakly typed languages are those in which variables are not bound to a specific data type. Just to be clear, this doesn’t mean that variables don’t have types. It just means that the variables are not bound to a given data type. C and C++ are good examples of weakly typed languages. Let’s look at the following C++ code:

int main()
{
    char c = 'x';
    cout << c << endl;
    c += 2;
    cout << c << endl;
   
    return 1;
}

In this example, ‘c’ is initially a variable belonging to the char type. In the next line, we add 2 (which is an integer) to this char variable. This is allowed in C++. The compiler won’t throw any error and you will see ‘x’ and ‘z’ printed in the output console. So just to summarize, Python is dynamically and strongly typed, and C++ is statically and weakly typed. Going even further, we can say that Java is statically and strongly typed and PHP is dynamically and weakly typed.

Isn’t dynamic typing risky?

The good thing about dynamically typed languages is that you don’t have to initialize variables. This seems like a nice feature to have, right? In fact, a lot of scripting languages have this feature. Dynamic typing saves you from writing extra lines of code, which, in turn, makes your code concise. But dynamically typed languages also have a major problem, and the problem is that they are dynamically typed. Now how can the same thing be a feature and a problem? Well, let’s consider the following example in Python:

first_variable = 12
second_variable = 0
for i in range(first_variable):
    if i < 7:
        second_variable += 1
    else:
        second_voriable = 0.5*(second_variable - 1) // spelling error

The variable “second_voriable” is misspelled intentionally to demonstrate the concept. As we can see here, second_voriable is obviously a spelling mistake. But the problem here is that this is totally fine in Python. Since Python is dynamically typed, it will treat this as a new variable named “second_voriable” and not return an error. So we have two variables here, second_variable and second_voriable. Now imagine spotting this kind of mistake in a large codebase containing tens of thousands of lines of code. This will be a huge mess! The worst thing is that sometimes it’s not even your mistake. Somebody else would have created a class somewhere with this kind of a mistake, and you might end up inheriting it.

So does that mean static typing is better?

According to the polls, Python is the most popular programming language in the world right now! So obviously people like dynamic typing. There are advocates of both forms of typing. On one hand, people like dynamic typing for its simplicity and it saves a lot of time too. They believe that type checking need not be an integral part of the programming language design per se. If somebody wants it, they can implement it separately. You can totally impose those constraints in your programs! On the other hand, people who advocate static typing say that static typing should be an important requirement of programming language design and that it leads to much safer code in general. C++ and Python are two of the most popular languages in the world, and they advocate different philosophies. Both these designs will continue to exist in the foreseeable future. It’s just a matter of choice as to what you would like in your project.

———————————————————————————————————

One thought on “Static vs Dynamic Typing

  1. Pingback: Why Is Python Slow? | Perpetual Enigma

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s