Static vs. dynamic typing of programming languages

Updated 2010-10-20 — added a bit more information about Boo’s type inferencing.
Updated 2012-04-08 — This post is an appendix to a post comparing Java and Python. Some comments on this post are actually comments on that other post.

There is widespread confusion or disagreement about the meanings of the words static, dynamic, strong and weak when used to describe the type systems of programming languages.

Here is a description of the way (or at least one of the ways) these terms are most commonly used.

In a statically typed language, every variable name is bound both

  • to a type (at compile time, by means of a data declaration)
  • to an object.

The binding to an object is optional — if a name is not bound to an object, the name is said to be null.

Once a variable name has been bound to a type (that is, declared) it can be bound (via an assignment statement) only to objects of that type; it cannot ever be bound to an object of a different type. An attempt to bind the name to an object of the wrong type will raise a type exception.

In a dynamically typed language, every variable name is (unless it is null) bound only to an object.

Names are bound to objects at execution time by means of assignment statements, and it is possible to bind a name to objects of different types during the execution of the program.

static_typing dynamic_typing

Here is an example.

In a statically-typed language, the following sequence of statements (which binds an integer object, then a string object, to the name employeeName) is illegal. If employeeName had been declared to be an int, then the second statement would be illegal; if it had been declared to be a String, then the first statement would be illegal. But in a dynamically-typed language this sequence of statements is perfectly fine.

employeeName = 9
employeeName = "Steve Ferg"

Python is a dynamically-typed language. Java is a statically-typed language.

In a weakly typed language, variables can be implicitly coerced to unrelated types, whereas in a strongly typed language they cannot, and an explicit conversion is required. (Note that I said unrelated types. Most languages will allow implicit coercions between related types — for example, the addition of an integer and a float. By unrelated types I mean things like numbers and strings.) In a typical weakly typed language, the number 9 and the string “9” are interchangeable, and the following sequence of statements is legal.

a  = 9
b = "9"
c = concatenate(a, b)  // produces "99"
d = add(a, b)          // produces 18

In a strongly typed language, on the other hand, the last two statements would raise type exceptions. To avoid these exceptions, some kind of explicit type conversion would be necessary, like this.

a  = 9
b = "9"
c = concatenate(  str(a),  b)
d = add(a,  int(b)  )

Both Java and Python are strongly typed languages. Examples of weakly typed languages are Perl and Rexx.

A third distinction may be made between manifestly typed languages in which variable names must have explicit type declarations, and implicitly typed languages in which this is not required. Implicitly-typed languages use type inferencing rather than data declarations to determine the types of variables.

Most static languages, like Java, are also manifestly typed.  But Frank Mitchell notes that some are not: “Haskell and the dialects of ML, for example, can infer the type of any variable based on the operations performed on it, with only occasional help from an explicit type.” Scala is an interesting new statically-typed language for the Java Virtual Machine that uses type inference

Boo is a Python-like language with type inferencing that runs on the .NET CLI. Here is a snippet from the Boo page about Boo’s type inference:

Assignments can be used to introduce new variables in the current scope. The type for the new variable will be inferred from the expression on the right. Only the first assignment to a variable is taken into account by the type inference mechanism.

The following program is illegal:

        s = "I'm a string"   # s is bound with type string
        s = 42               # and although 42 is a really cool number s can only hold strings
About these ads

43 thoughts on “Static vs. dynamic typing of programming languages

  1. Hi Stephen,
    What this misses is any mention of the Static Type Checking vs Dynamic Type Checking arguments.

    You know, the “Poor dynamic languages you don’t get the benefits of a static type checker and so must exhaustively test your program or ship crud” versus the “Actually you are deluded in substituting type checking for program testing. You are much more likely to ship it when it compiles” and the not as common: “If static type checking were so good, how come most of the people using static typing use languages that are not type safe? Static type checking is an ideal that fails in the real world”

    Therse seems to be a stream of “new programmers” (that have the static mantra pummelled into them by educators that should be more aware), that think it is their job to “correct” positive mentions of dynamic languages on Wikipedia for example. Oh well.

    P.S. I liked your use of graphics.

  2. I’ve been trying to explain this to people for a looong time. When they hear about dynamic typing most will think of Perl or JavaScript, both of which are dynamic and weakly typed.

  3. There some things that made me conclude that Java is easier than python

    1) Good documentation. Yes python has a very simple syntax , while java is more verbose but nothing can make thing any easier than good documentation, especially with third party libraries. Many of them actually require their users to read C++ documentation that defeats the purpose of using python in the first place.

    2) Speed. Python is very slow, and even this does not show very often only for CPU intense tasks , that does not mean that python does not consume too much CPU. Again this might not be the problem for non intense CPU stuff, but because I working with midi and audio it makes my life harder.

    3) Lack of a good IDE, IDEs is an essential part of RAD and none of the IDEs that support python works in a way that is hassle free. Especially in the GUI design department these IDEs leave alot to be desired.

    I love the python syntax, it is surely the best of the best, that is why I have jython close at hand , but overall, at least for me what killed python is bad documentation and fragmented cross platform availability of libraries ( I have even experienced severe problems into making python work on macos).

    I dont see python conquering the universe, the best language is yet to be invented. Its a great language however and alot of fun to use.

  4. Just my 5 cents.

    I am python coder and java coder all together for many years. In fact, you are just biased. You literally forgot that static typing is way better for large scale projects (which Java is designed for). Python will break into pieces as soon as project will thrice exceed a size of Zope and Plone taken together. Anyone argues here how fugly Plone code is inside and how buggy it is? Same valid to JSP: this part is fragile enough, because it is dynamic, although IDE is trying hard to resolve potential problems on a fly.

    I see Python is extremely excellent Perl/Ruby replacement on infrastructures. As well, Python is very good to compete with PHP on simple webthings. However, if you gonna write really-really complex things, at least try to be modest and remember that simple fact that Google writes its code mainly in C++ and Java, despite Guido Van Rossum is employed there for years.

    You also forgot that Java is quite old language and significant innovations are rejected due to a number of reasons. First of all, it is for Enterprises and is still there and will be for sure for a many years. If you add new stuff there — it will not be a Java anymore (closures, for example). Java folks voted *against* sweet things although they *do* understand it could be nicer to have them.

    And be honest to yourself: the best cross-platform IDE for Python so far: NetBeans IDE with Python/Jython support. You just install on your favorite platform. And it just works as you expect.

    P.S. And one more dirty secret from Python world: they use Hudson for tests and builds. But nobody says it loudly, because it is also written in Java. ;-)

    • Python’s no good for large-scale projects, huh? How about this from Thanos Vassilakis, then a programmer for NYSE:

      ———–
      ” On the New York Stock Exchange we use three languages in production to deliver serious trading services to the Specialists: c, C++, Python.
      Perl, tcl/tk, Java are used but for scripting, tools, and minor services where performance and memory foot print are not an issue. Yes, used correctly Python meets our performance, security and reliability requirements.
      We have had Java projects and launched Java services, they have all failed. We have many in the pipeline (thanks Big Blue) but NYSE’s only serious internet based service is written in Python, and was launched in 1998. It is still up in it’s sixth version, with no down time! The fifth version was rewritten in Java, 6 months overdue, failed, and replaced by python ( which took two weeks).
      Here at SIAC and NYSE Python is recognized by management to give results that other languages just can’t achieve.
      For performance we have extended Python with our own specialized c objects, and we have used swig extensively to integrate to our legacy code, and middleware.
      Thanks Python, you let me get home to my kids.”

      • A large scale project that takes 2 weeks to build? That’s just ridiculous.

        I like python, but dynamic languages can only go so far when you start hitting hundreds of thousands of lines. Then it becomes a bitch to maintain. It doesn’t scale well in that aspect. Refactoring and static typing becomes your best friend when you start working on projects that involves thousands of classes.

        I’ve worked with enterprise applications all my life, I have yet to see python or any dynamic language used as the main language.

        • Try Python. You might be surprised at how often the mindset of the Python programmer leads to solutions that don’t require hundreds of thousands of lines of code.

          As problems get bigger you can measure bottlenecks and replace the bottleneck with routines written in other languages but still controlled through Python.

          Remember, the goal is to solve the problem.

          • Obviously you haven’t worked on an enterprise level application. Try working for a bank, financial institution, or the airline industry. There’s no way around it, no matter what language you use.

            • Oh, I work for an enterprise. And my software needs to deliver. One of your rebuttal replies was from someone in the banking/financial industry.

              I guess Python will remain a “secret sauce” for your companies competitors.

  5. BM,
    You need to be wary of a Java mindset that might attempt to solve too many problems with large solutions. This wastes any advantage the language compiler may have in execution speed, or the ability to allow many programmers to solve a problem.

    As for Java’s “Enterprise class” credentials, be aware that some may think of “enterprise” as a byword for buggy, bloated, expensive and late.

    There is a niche for Python, it works well on its own or in conjunction with other languages such as Java, C#, C, and C++; and over the years, the niche of Python and other dynamic, scripting, languages has grown – which I think of as being a good thing.

  6. Paddy3118,
    Yup. That’s what I am talking about: Python is just excellent tool for building up infrastructures. IPS for Solaris is written entirely in Python, including GUI. Same to RedHat’s Anaconda stuff and a whole Yum thing. There are many examples like this, where Python still fits much better than Java due its dynamic nature.

    However, I think I already grew out of wearing disposable diapers, in order to compare two technologies for quite different targets just by number of codelines… Yes, Python is very sweet at syntax, but it is also very painful on CPU and memory use as well as overall performance, when you misusing it. Same as Java: it might be extremely powerful, solving lots of problems where C/C++ folks will struggle for months, while it also can be very painful, where same task can be solved in minutes, using Python.

    That’s why I use both of them: Java for software development and a Python for building infrastructures that manages that Java-based software.

  7. BM, Python is a “glue” language that help us stick others programming language together. So there is no problem if they use C++ and Java to build something that python use for its Apps, that make a good control over lots of thing.

    Just like a commander and soldiers.

  8. Type checking saves your butt seriously. The pleasure of saving a little typing and careful thinking does ensure the disaster later. Unless you are borrowing code from others who got their butt kicked already for that code. :-) Sometimes, some things look cool but they are actually dangerous and not cool at all, and some things look clumsy and ugly but they are actually very cool.

  9. I am not a programmer. I dabble in Tcl/Tk, but can’t claim any especial skill in it. However, I work for a large corporation that makes extensive use of Java based “enterprise” applications, and they all uniformly suck to one degree or another. I am not in the IT department. I am just a lowly shop floor grunt in a factory.

    We have Lotus Notes 8.5, which has a prominently displayed java logo on its splash screen. Lotus Notes is awful! It has a weird, non standard UI (tho it is getting better), the UI is cluttered, and has lots of extra crap that most people will never use. It is constantly telling me that I have email when I don’t, or when it starts up, it will randomly mark emails that I have already read as unread. Its slooooow.

    There is a database on Lotus Notes that I have to use for my job. Again, the UI totally sucks. There is a form that I have to fill out on a regular basis, and there are items on this form that NEVER change, yet I can’t save a “draft” of this form with these items already filled in. I have to type them in every time. I may fill out this form 20 times or more on any given day. There is also a ton of stuff on this form that I never have to deal with, yet I still have to scroll through all this extra crap to get to the items I actually use. In addition, it has a somewhat non-standard UI, that doesn’t behave the way one would expect for the rest of the Windows environment.

    Next, we have this lovely java based web app to access an Oracle database. To make use of this abortion of a program, one has to have THREE browser windows open, one of which does absolutely NOTHING, it’s just a place holder for the main window, wherein you actually do your work, and if you close this “unused window”, it shuts down the whole app. The main window, nothing works as expected. For example, pressing ctrl-A to select all items in a database field doesn’t work. Lots of stupid and annoying pop up windows. Closing a window inside the work area isn’t possible if you have typed anything into a database field. You have to erase the field, then close the window. Stupid!!! And the UI on this thing is just plain butt ugly. It is also extremely slow, and takes forever to log into, which you have to do a lot, since it kicks you off if it is idle for more than a half hour (this is what the third window is for, logging back in…and that is ALL it is for…)

    We also have another custom web based app that accesses the same database mentioned above in the section on Lotus notes, the app is made by some outfit called NDS systems. It opens two browser windows, again with one that doesn’t do anything, but you can close it because it will shut down the app. Again, UGLY, non-standard UI. Lots of buttons, no tool tips to tell you what the heck they do. NOTHING works as expected. The UI is very unintuitive. We have to use it to access a specialized label printer. Heaven help you if something goes wrong and the label doesn’t print. You have to jump through a bunch of hoops…very unintuitive hoops…to try and reprint it.

    Then we have IBM Maximo. Same issues as mentioned before, but to give this one credit, it at least uses only one browser window. UI is, as expected with a java app, Ugly, slow, and unintuitive. One function we use Maximo for is to order stuff from tooling stores. The process of choosing what you want to order is overly complicated, and yet again, extremely unintuitive. For example, to actually order an item, you go through the complicated process of finding it, then you click a button that says “Return With Value”. How stupid is that? What would be so hard about making the button say “Order Item”, or “Add to Cart”? If an online business used something like this crap, they wouldn’t stay in business long.

    In short, enterprise java apps sucketh muchly.

    I have seen only one java app (not “enterprise” related) that wasn’t too bad, and that is Jave (an ascii art program), and even it seems a bit unituitive at times.

    I imagine java is just the “bees knees” for IT department types and programmers. But for those of us who actually have to use apps written in it on a daily basis, it appears to be an abysmal choice.

    • In reply to: Elwin (2010/08/29 @ 8:24 am) …”abortion of a program”

      HAHAHAHH!!! LMFAO!!! Never heard that one before, but with your permission will borrow it heavily in the future for any piece of crap software.

    • While those programs sound pretty bad, the terrible quality of those programs isn’t the fault of the language, rather, the fault of the programmer.

      • Not really the fault of the programmer but the fault of the Product Manager. They should have assigned a good UI/UX guy on it. The programmer only develops what is assigned to him.

  10. Those looking for a good Python IDE, try PyDev plug-in for eclipse. Eclipse is Java as everyone would know…

    My first choice of programming languages on new projects is Python. My reasons are I like its dynamic nature and the productivity I get out of it. Some have mentioned that Python is too slow for CPU intensive tasks. I use C++ for that, as it is trivial to write the needed interface between the C++ and Python parts of the app. It is only ever a very small percentage of the app that is too slow.

    However I do think Java has its place. One is when there is some excellent library that exists for Java, but is lacking in Python or C/C++. There are some, and they can save a hell of a lot of work. The other is is a large code factory. Java with all its interfaces and static typing makes quality control with a lot of mediocre coders much easier, where as with Python with its highly dynamic nature quality is something you have to work at.

    I realize this post is very opinionated, but I don’t really care to back it up with hard evidence, it just comes from my experiences.

  11. [This, and another comment by the same author, have been edited or deleted because they contained inappropriate language or abusive comments. What follows is an edited version of the comment.

    I will not accept comments containing inappropriate language or abusive comments on this blog. The only reason that I edited this comment, rather than deleting it outright, is that other comments were directed to this one.

    So, in general folks, let’s keep it civil. If you can’t keep it civil, your comment will be deleted.

    — Steve Ferg]

    Python, easy to maintain? Yeah, for a one-man development team, which is about all you’ll need since productivity gains > 500%.

    But try debugging someone else’s code in Python…

      • Jmaik,

        Static typing is more precise, but harder to read, because there is more code clutter. Python was designed to be read easily.

        What I meant was that if they made a mess of a python program, then maybe they shouldn’t be writing code.

  12. The title of the article tells you the Author is biased. Being objective and well versed speaks a lot to how well learned a person is. On the other hand, making biased arguments and conclusions only diminish your understanding.

    You write an article on ‘typing’ only and conclude that one language conquers the other as a result of different style of typing. I’m in a hurry to pick my family from the airport, but I’ll be back with something we all can learn from….

  13. Um… newsflash but you are comparing an interpreted scripting language to a compiled language; to properly compare, why not use a JAVA scripting language like Groovy? In which case, most of these comparisons would be the same or similar. Unlike Python, Java has an answer for the situation and need… it’s just that people outside of the Java community aren’t as informed since Java is a vast (choose one) system/conspiracy

  14. The examples on this article are not good ones or not written correctly.

    Like why would compare an int to a string? I can’t think of a time I would do that. If this is a user input, you should ALWAYS have validation and only allow numbers to be typed. Another solution is if you’re expecting something more than just digits (you would know this even before coding), then why use int in the first place to hold the value? You can use String right away and just compare directly.

    Another BAD example is the for loop that displays a count from 1 to 10. Just drop the curly braces and you have the same line numbers as the Python code. Curly braces are not required unless you have more than 1 line of code inside your loop.

    Am I missing the point?

    FYI, I don’t use Python. I can’t help but react to the examples used though. It doesn’t give the Java syntax credit at all. There are many ways to write Java code. The python code may be shorter, but with the use of IDEs (eclipse, intelij & netbeans), writing verbose Java code may even be faster than writing short python codes.

    • Unfortunately Jay, code has to be maintained and the more there is to maintain, their more difficult that task is for most languages. (APL and J might be exceptions).

      The problem with machine generated code is that it can be easy to generate more code leading to bloated programs.

      The web site Rosetta code has examples of many tasks completed in both Java and Python. You might want to look at examples from here to compare Java with solutions in dynamic languages. The examples are written by those interested enough to write or improve them rather than say an expert in one language moving tentatively into another.

  15. Java evolved to address issues that arise in the development of large systems. The emphasis is on discipline and structure. The language does not aim at making the writing of small or medium sized programs easy and fast.

    Comparing Java to Python is like comparing a sports car to a truck. Which one is better? The truck is better for some things, the sports car for others.

    Learn both languages and use the one better suited to do the job at hand. Partisanship shouldn’t play a role in computer science.

  16. Java is so “fragmented”* that any Java newbie will struggle to pick-up those fragments and spend time in putting them together rather than using Java to build powerful applications

    Secondly Java is a resource hog period.

    http://dl.dropbox.com/u/17748204/JAVA_HI.AVI

    In the above clip someone from Sun Microsystem talking about ‘Code Rot’. many years later Java signifies Programming Language Rot!

    Now Drink this! http://dl.dropbox.com/u/17748204/javaarch.avi

    *POJO’s, Beans (EJB)

  17. Being a C++ and Java programmer, I have written plenty of programs with data type problems and bugs. On one hand it is easier to code with Python and on the other there is a lack of consistency with your data types. With Java and C/C++, you have to explicitly declare variables and specify their data types prior to usage. This can be a pain, but it gives you a little bit more control of your program(in my mind.) In Static vs. dynamic, it just comes down to which you find is easier. (In my opinion, I prefer Static typing over dynamic. Having to declare variables before usage is second nature to me and I don’t mind it.) –Andrew

  18. Real life question:

    After not being a programmer since 1985 although I did learn some C++ in 1999, I am thinking of going back into programming. I never had any real systems skills, we had systems admins or systems programmers in those days. I have programmed in the other following ancient languages PL/1, Pascal, COBOL (not counting IBM 360 Assembler). I never counted some of the command languages as “programming.” Back in the day before then you needed Job Control Language which I was able to mostly skip. I actually started programming on punch cards. I am really unclear on whether I should try Java or Python, after reading a few articles I am wondering if Python basically can do what PHP, Perl, Java and JavaScript can do and also just upgrade my C++ skills at the same time, just in case. I am not really buying the Perl or Python is really Lisp reincarnated and I hate to say that after reading a number of these comparisons I think Java now has taken object oriented programming to a place I don’t want to go. Originally people just wrote with gotos. It was pretty ugly if you had to modify someone else’s code.

    The way I see it, writing and using private classes and constructors has now gone to the complete extreme pole and is so bulky that every time someone writes a program he or she is really forced into creating object classes. All the database stuff seems to be SQL layered into a language.

    I doubt I am going to be writing anything too extensive but I will want to write some PC based applications and some web applications so what should I do or what advice would you people here give to someone in college who wants to write apps but not what I call Operating Systems such as Windows or Unix. I also am wondering what games are written in these days or if you need to use libraries of C++ code. For the moment I am leaving out objective C as well.

    From what I am seeing you can get a WAMP package with everything (a system) ready to go in a day and move on. I don’t see all of that with Python.

    Dave Van Winkle

  19. Great article !! I’m learning with all of your posts, not only the ones about Python.
    Thank you for sharing all your knowledge.

  20. this is a wonderful discussion ..but what i can simply interpret from all the discussion is that, when you start making a application and you have less resources probably yourself you should probably start with python so that its easy to implement your ideas (LIKE Facebook.com was built in PHP in beginning ) but when later on your application starts growing massively and you can switch to other language like JAVA as you have resources you can find ways to get your code converted ( like now Facebook.com uses lot of optimization in its codes in C++ and Java) . … SIMPLE :)

  21. Nice article.

    I just joined a large research collaboration that does most of it’s work in C/C++, Python, Matlab, PHP/Javascript, Mathematica and a few others but almost no Java.

    I am working on a position paper with the opposite conclusion that Java should be added to the mix. I have only a few Python tutorials under my belt and no production work. You’ve convinced me that I need to do at least one good sized Python project before I finish my comparison.

    I would not argue that Python should be replaced but I tend to agree with the comments by Bosco and Paddy3118, they both have their place, depending on the complexity of the project

    I am a big fan of refactoring, self documenting code, good IDEs and have to write cross platform code. I like a lot of compile time checking but agree it doesn’t replace run time checking. Anyone who ships code when it compiles or runs the first time is foolish.

    I’m working on a medium sized Matlab project, written by several before me, right now and have been bitten by rare occasions where a character array is expected and a cell array of characters is passed instead. Strong static typing has helped me more than it’s hurt me, but I understand the attraction.

    Conciseness and clarity are often incompatible, taken to the extreme we have APL which was often described as write only code. In my world writing the code is a small part of its life cycle and most of the time I can type faster than I can think so a few curly braces and a file per class don’t register as time wasters. It’s much more important to me to be able to track down bugs and understand the interaction between modules.

    Thanks again for the informative article. I personally don’t think any programming language will become universal any more than I see Esperanto taking over human communications. There are just too many things that can be expressed better in one language than another.

    Joe

  22. Nice article, though the bias against Java could have been tempered. A Swiss knife programmer needs to have different tools based on size, scale and scope of a project.

    • I agree about the comment on tools. In fact, I wrote

      Programming languages are tools, and different tools are appropriate for different jobs. It is a poor workman whose toolbox contains only a hammer (no matter how big it is!), and it is a poor programmer (or software development organization) whose development toolkit contains only one programming language. Our toolboxes should contain both Python and Java, so that in any given situation we have the option of choosing the best tool for the job.

  23. Small benefits in writing slightly more concise code in a scripting language do not outweigh, nor ever will for that matter, the long term benefits derived from strong typed languages.
    The fact that you feel oppressed by not being able to assign to a variable any type of object/function like you can in scripting languages like javascript/python is a tad revealing of a lack of strong comprehension of design patterns and proper software design.
    You should know that with Abstract classes and with parameterized/templated classes, you can make you solutions as generic as you please, as long as you have the creativity for it.
    The IDEs, debuggers frameworks, standards and libarries for these languages, in particular Java, are the best and most mature in the world.

    Javascript, for example, is a very nice an flexible language, I like it and find it comfortable to use. I like it even better if I let Google compile it for me from a stronger typed language. However, what I do dislike is the abhorrent code I see programmed in it every day. You can believe me, a Programmer that programs badly in Java will make code 100 times crappier and harder to debug in a scripting language like Perl, Javascript and Python.

    • But remember that design patterns show up deficiency in a languages design. – better languages have less need for the boilerplate code bloat of a design pattern and instead have subsumed most of that into the syntax of the language.
      The IDE’s need to be good when the language is so poor. It acts as a crutch to keep the language going. Somehow, too many Java programs are large and complex. With the amount of multi million pond computer systems that are junked each year maybe Java the language steers its programmers to habitually overreach themselves (and their “proper” design)?

      P.S strong typing does not equate to static typing. Python is both strongly and dynamically typed.

Comments are closed.