0

I heard (from Robert C. Martin) an assertion that since dynamic languages don't have static typechecking, people should write unit tests to prevent us from type errors.

I'm not sure if I'm following the thinking here. Could anyone exaplain HOW? Could you give me one concrete example?

  • 1
  • thanks for the link, read it, but still it didnt completely answer to my question. Q: give me one example of problem that cannot appear in Java, but can in javascript, and what kind of unittest do i need to writ to avoid taht – Tomy Mar 5 '15 at 22:58
  • 1
    It doesn't prevent type errors, although it does reduce their occurrence. Static type checking is a compile-time guarantee, within the scope of the type checking. The only thing that unit tests guarantee is that your tests test what they are designed to test, if you wrote them properly. – Robert Harvey Mar 5 '15 at 23:21
  • type errors or typing errors aka typo. Methinks those two are different – Brandin Mar 6 '15 at 22:11
0

A good example for this comes from code I have seen recently:

if foo
    bar == baz
    # should be bar = baz

In python expressions like this work totally fine but they don't do what you intended.

Another typo in the same code:

class foo:
    ...
    def bar(self):
        ...

def foo_bar:
    ...

...

foo.bar()
# They meant to use foo_bar()

Sure this is caused by bad naming but the bug could have been spottet using tests. Simple tests could have uncovered that the if statement simply does nothing.

3

Unit tests don't actively prevent type errors, but they do provide you a mechanism to execute the code you have written before the entire application is complete.

If you try to do something silly, like mistyping calculateInterest as claculateinterest, then that will be caught early on if you use a statically typed, compiled language like Java because the compiler will complain loudly.
If you do the same in a dynamically typed language, the error will not be noticed until that line of code actually gets executed.

If you don't write unit tests, then it can be weeks before the application is finished far enough that your feature can be executed and tested in the complete application. That is a very long turn-around time for finding such silly mistakes.
On the other hand, if you do write unit tests, then it is mere minutes between writing a module and executing it. This has the huge advantage that the code is still fresh in your mind and that you are not yet fully occupied with writing other modules.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.