Static typing VS. Unit tests

Okay. It’s kind of stupid to put static typing up against Unit tests. Even so, lots of people does so a lot of times in the discussion between dynamic and static programming languages.

Static typing provides you with a security net when it comes to typos. Alhough, it doesn’t give you any security against logical errors.

I’ll give an example

?View Code JAVA
public static Foo{
  private int stored;
  public Foo(int bar){
    self.stored=bar;
  }
  public void increment(){
    self.stored +=1
  }
}

compiles fine

?View Code JAVA
public static Foo{
  private int stored;
  public Foo(String bar){
    self.stored=bar;
  }
  public void increment(){
    self.stored +=1;
  }
}

Will give you an error already when you compile the class, because you attempt to store a String onto a property that will only accept integers. And if you use an IDE, it will notify about this error already when you write the code.

Now let’s do the same with python.

?View Code PYTHON
class Foo:
  def __init__(this,bar):
    this.stored=bar
  def increment(this):
    this.stored +=1

This looks perfectly fine, doesn’t it?

You’ll think so, and so will the IDE and the “compiler”.

Now execute this code as follows:

?View Code PYTHON
myfoo=Foo("shrubbery")

Still no errors.

Now, what happens when we call the increment method?

?View Code PYTHON
myfoo.increment()

BANG! now the code fails. What if your product could run for weeks before the increment method is called? You might have landmines in your code.

In this case static typing would have catched the error, but consider the following code:

?View Code JAVA
public static Foo{
  private int stored;
  public Foo(int bar){
    self.stored=bar;
  }
  public void increment(){
    self.stored + 1;
  }
}

This code will compile fine, and it’ll even run fine, but the result will not be as expected.

Writing programs in dynamic languages like Python without an extensive test suite is hazardous. Its even so hazardous that hardly anyone with some experience would even think about writing programs without it.

In the world of staticly typed languages programmers are lured into a false sense of security and may even never learn the habit of writing unit tests.

However, that being said. There is a lot of times I would love to have static type declaration in Python, or at least type hinting on method declarations. That would relieve us of all the libraries that has functions that takes “things” as arguments, and returns an enumerated list (tuple) of things. But I guess there are more that speaks against this than for it.