Shyam has posted 8 posts at DZone. You can read more from them at their website. View Full User Profile

Is Strong Typing Really Needed?

03.05.2010
| 6861 views |
  • submit to reddit

This is something I have been struggling with for the last few months. I have had people argue ardently that all Strong typing is good for is false comfort and lots of unneeded typing. But I was strong. I was undeterred. I dismissed this as the crazy rants of those JS developers, those dynamic language people who believe that obfuscation and compactness is everything, even at the cost of maintainability. I mean, how could a language where you didn’t even know what was getting passed in in any ways better than something where the APIs are explicit and stop you from making mistakes. A dynamic language could work for a single developer, but definitely not for a team. That was my whole hearted conclusion.

Now, I’m not so sure anymore. Its been 3 weeks since our team made the whole hearted switch. Has it been roses and sunshine? No. But it hasn’t been as bad as I expected it to be. And there are a few reasons for that. But before that, I’ll lay down the pros and cons the way I see them from my (assuredly very limited) experience 

Benefits of Strong Typing :

  1. Errors / Warnings in your editor
    Simply put, this might just be the single most greatest benefit of strong typing, and the single reason why most java developers (a lot rightly so) will never even consider leaving the safety of strong typing. While compilation support doesn’t necessarily go hand in hand with strong typing, most people tend to associate Java with it, so lets run with that. Simply put, with Strong typing, your editor can (and should, I mean, if you are not going to get immd. feedback, what’s the point?) give you immediate feedback when you messed something up. Whether this be using the wrong variable name or trying to call a method that either does not exist or with the wrong parameters. Or if you are trying to use the wrong type of object.

    To a Java developer, an IDE like Eclipse or IntelliJ is godsend, as it tells you what is wrong in your world and lets you jump to them, gives you suggestions and autofixes and generally makes your life as painless as it can. And it is brilliant, I can tell you that.

    In Javascript (or any other dynamic language), everything is fine and dandy for the first 100 lines. After that, it becomes scarily unmanageable. The only way around this that I have found so far is to be super paranoid and write tests for every single line of code. If you can’t do that, stay far far away.

  2. Generics (but this is also a negative, in my opinion, which I’ll get to below)
    The idea behind generics is that gives developers some assurances about the types in a collection (or whatever it is you are genericizing). That way, all operations are type safe, without having to convert to and from different types. And you are assured that you will not be surprised suddenly by a different type of object popping up when you least expect it. But there are a lot of issues with them that I’ll cover in the second section.
  3. Ability to follow a chain and figure out what type of object is required at each step
    Now this is something I definitely miss in languages like Javascript and Python. The fact that I can trace (in my IDE, note that part) what the type of each variable / method call in an expression chain is simply amazing, especially when you are working with a new codebase. You never have to wonder what the parameter types of the method you are calling are. You don’t have to wonder what methods are available or visible. You just know this information (Again, assuming you are using an IDE. If not, god help you)
  4. Refactoring

    The biggest advantage of Strong typing though, in my opinion, is the ability to create IDEs which make refactoring a breeze. Renaming a method / variable? Trivial. Moving or extracting a method? Simple key combination. Stuff which can be extremely tedious and mind numbing are accomplished in a matter of minutes. (Want to know more about these shortcuts? Check out Eclipse shortcuts). This is simply not possible with languages like Python and Javascript.

Disadvantages of Strong typing :
  1. More concise and precise, less typing
    Dynamic languages do tend to be more dense, and it is much easier to accomplish in 10 lines what can easily take 50-100 in a language like Java, which is especially verbose. Consider trying to pass in a chunk of code to be executed at the end of a function in both Java and javascript (this is pretty common in web apps and task runners)
    Java :
    interface Function {
    T execute(); // Optional parameters is not easy here :(
    }
    taskRunner.execute(taskArgument, new Function() {
    String execute() {
    return "Success";
    }
    });

    Javascript

    taskRunner.execute(params, function() {response="Success"});
  2. No badly implemented generics

    This is mostly Java’s fault of getting generics pretty badly wrong. The idea behind generics is sound, its the implementation that is horribly broken. Here are a few things which are wrong with it :
    Type erasure : This basically involves the fact that at runtime, there is no way to differentiate between say, a List<String> and a List<Integer> If you never work with reflection or Guice, then this might not be a problem. But it also is a pain with deeply nested generics and wildcards. I have seen compiling code which blows up at runtime because it cannot differentiate between a Provider<? extends Repository> and Provider<? extends Resource> and neither Resource nor Repository have anything in common. Crazy….

    Verbosity : Map<String, List<String>> myMap = new HashMap<String, List<String>>();. Enuff said.

    Guice & Reflection : Generics and java.lang.reflect just don’t mix. They just don’t. Type erasure blows away all type information, so you are bound to be using stuff like new Entity<?> which totally defeats the purpose. And don’t get me started on Guice. In guice, normal bindings (non generic classes) look as follows :

    bind(MyInterface.class).toInstance(instance);

    With Generics involved, they now look as follows :

    bind(new TypeLiteral<MyInterface<String>>(){}).toInstance(instance);

    What the heck just happened there???

  3. Closures / Functions :
    Closures are a form of anonymous inner functions which can have an environment of their own, including variables bound to the scope of the function. The inner function has access to the local variables of the outer scope and can change state. But what it does allow is creating functions, as callbacks or for performing some quick little task in a repeated fashion, easily and quickly and pretty darn cheaply.Java has had a few proposals to add it (http://javac.info/) but it has not passed the review committee yet. And probably won’t for the next few years. So till then, in Java, you are stuck creating interfaces, creating an implementation of it at runtime, passing in variables you need access to in the constructor or through some other mechanism, and generally be in a lot of pain. Thanks, but no thanks.
From http://theshyam.com
Published at DZone with permission of its author, Shyam Seshadri.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Osvaldo Doederlein replied on Fri, 2010/03/05 - 3:18am

It's static, not strong, typing that you are talking about. JavaScript and most other modern dynamically typed langs are strongly typed.

Endre Varga replied on Fri, 2010/03/05 - 3:18am

Well, the disatvantages are not the disatvantages of Strong typing, just their Java implementation. Scala does not suffer from these (except type erasure -- this comes from the JVM).

And Bod replied on Fri, 2010/03/05 - 5:13am

You know I really think I'm gonna make it a rule to NEVER read stuff on DZONE, and it's because of people like you, and the first guy who answered your article, and let's not forget the other one  a few days ago who just blurted right out a post declaring that the JAVA EE SDK is a p.o.s.

I don't mean to be rude but most of you people write meaningless and mindless rants, who not only are useless but also simply false, denoting that you really don't have any development insights past a little scratching the surface/diletantism involvment.

 First off, guy who made first comment on this article: NO, he is talking of strong typing which means that the language cares what type of parameters are passed around. Static typing refferes to WHEN the checking is made, either at compile or run-time. The difference between java and php is that php accepts anything in a method call, runs with it, and will only err if we try to do something with that parameter, inside that method that the parameter doesn't support (like call a method that doesn't exist). Java won't let you compile and run that because it sees the types don't match.

 Then, guy who  wrote this article. Will you be saying next that OO programing is a big lie and procedural is the way to go? I'm not gonna point out how wrong you are and how much of a strow man's argument you put up here cause that would take too much time. I'm just gonna say these 2 things that you can ponder upon:

 

1. After working for years in Java,  I've done a 6 month project in PHP. It was a nightmare for many many reason, much  more then those you listed here and it had none of the "pros" of the weak typed languages that you list here

 2.  Hey you don't have to listen to me. Look at Google. Google, ok, the king of java script. What did Google do. It made GWT, a java wrapping over JS. Why did it do it? Because he realised it was simply cumbersome and unwealdy to develop stuff without the strong type benefits.

 

Ricky Clarkson replied on Fri, 2010/03/05 - 5:27am

What you are complaining about is that Java is shitty. Take a look at Haskell, Scala and even C# to some degree for better languages that don't lose type safety. Closures have nothing at all to do with being strong or statically typed. Read up on 'the untyped lambda calculus' and 'the typed lambda calculus'.

Christoph Kutzinski replied on Fri, 2010/03/05 - 5:37am

Agree with bart6425 and Ricky.
BTW: IMO 'disadvantages' 1 and 3 have not or only very peripheral to do with strong typing. They're simply about that Java has no closures - yet.

And disadvantage 2 not about strong typing, either, but about the bad implementation of Generics in Java (agreed on that one).

So where are the arguments against strong typing at all?

Oliver Plohmann replied on Fri, 2010/03/05 - 6:29am

"It's static, not strong, typing that you are talking about." Yes, unbelievable how often this is getting confused. Java will have closures in JDK7. Communicated by Sun months ago. The debate whether dynamic or static typing is most suitable is decades old and has only resulted in endless religious wars and no fruits. I have worked for almost 10 years with Smalltalk, which is dynamically typed. I once worked on a shop floor control system using Smalltalk. Very challenging and fun, very difficult to get the logic right. I think we had in production many errors in the logic, but almost no error a compiler of a statically typed language would have found. Then I had to change to working with Java and I enjoyed a lot the productivity of being able to change tons of code and after all compiler errors were fixed things work again as before. This, of course, is not always the case. But it is a big difference to Smalltalk where every developer after a little change immediately runs a test to see whether things still work. What Java is missing to be very productive IMHO is hot code replacement working 100%. To me hot code replacement always working in Salltalk is the main reason for Smalltalk being that productive not that much dynamic typing.

Fab Mars replied on Fri, 2010/03/05 - 6:52am

...and here we go again... the only "strong" thing I see here is  the BS.

 here again: bart 6425 +1 !

 

 

Jevgeni Kabanov replied on Fri, 2010/03/05 - 6:57am in response to: Oliver Plohmann

What Java is missing to be very productive IMHO is hot code replacement working 100%. To me hot code replacement always working in Salltalk is the main reason for Smalltalk being that productive not that much dynamic typing.

 You should try JRebel http://jrebel.com

Alessandro Santini replied on Fri, 2010/03/05 - 8:14am

Reading this article, I really do not understand where the disadvantages of a strongly-typed language are. Most importantly, there is no reference to any other strongly typed language but Java.

Speaking about virtues/fallacies of strongly-typed languages and giving only one language as an example, it is not really smart.

After the Assigner Pattern, this article is a strong contestant for the "Javalobby Darwin Awards".

Mac Pudding replied on Fri, 2010/03/05 - 8:49am in response to: And Bod

Very well said bart. This article tells more about the quality and experience of the author Shyam Seshadri than about the use for strong typing in Java.

Rok Končina replied on Fri, 2010/03/05 - 9:35am

Guys, don't be so harsh!

Shyam's observations are in fact correct although they don't necessarily apply to all languages.

But I definitely noticed the same good/bad differences between Java and Javascript.

Claude Lalyre replied on Fri, 2010/03/05 - 9:47am

Hi guys,

 No need to argue ! I think that this article is related to the  difference between Groovy and Groovy++. Groovy is statically typed and more slower than Groovy++ that is not statically typed. The impact of strong typing and static typing is a matter of performance and a matter of verbosity of the code.

 That's all ! And that's the reason why someone has decided to rewrite the Groovy language in order to have more efficiency...

2 issues

1) performance

2) verbosity

 

 

 

 

Osvaldo Doederlein replied on Fri, 2010/03/05 - 9:55am in response to: And Bod

I don't mean to be rude either, but you should RTFA again. The article is obviously discussing static typing when it says "strong typing"; let's see why:

- The article explicitly confronts "strong typing" to dynamic typing; this makes no sense as both concepts/options are orthogonal (we have have any mix of static/dynamic-typing and strong-weak-typing).

- The article never mentions any characteristic of weak typing (the opposite of strong typing).

- "how could a language where you didn’t even know what was getting passed", refering to a language that does NOT have "strong typing". He is talking about absense of type signatures that allow compile-time checks of parameters etc.; in a "strong-typed" language, "the APIs are explicit and stop you from making mistakes", referring to compile-time checks.

- You realize that generic types (advantage #2) are a feature exclusive to static-typed languages, right? The interpretation that the author really mean "strong typing" here, again makes no sense. Also, only static typing enables the IDE features from advantage #1. (Modern IDEs can now do similar tricks for dynamic-typed languages, but that's a recent development that relies on massive effort [type inference etc] from the IDE; it's not 100% complete/reliable as for static-typed languages and will never be.)

- Advantages #3, #4: Once again, clearly specific of static typing. (Again you CAN have them for dynamic-typed languages; in fact refactoring was born in Smalltalk-land. But it's never complete/reliable. I wouldn't trust in a complex refactoring, e.g. reorder method parameters, performed by the IDE on a large codebase of a dynamic-typed language. With a static-typed language I can trust the IDE to do that and just commit the changes without the effort of manually checking if the tool didn't make any wrong change, or didn't miss some change.)

Jose Maria Arranz replied on Fri, 2010/03/05 - 11:15am

I'm getting bored about these nonsense kind of articles talking about how bad is statically typed languages, dynamic languages are fine for the most dynamic parts of an application or to provide some kind of extension (scripting), the hard fact is I'm not going to see NetBeans, Eclipse or Visual Studio, Open Office or MS Office coded with a dynamic language, and is not peformance the most important issue.

It sounds for me like a bricklayer ranting about how much uncomfortable are his security protections. Crazy.

On the contrary I would like to see people promoting some kind of optional new extensions using annotations to the Java compiler to improve, enrich and increase the kind and number of checks the Java compiler executes. Public, protected, private are fine but they are too anemic.

The Java compiler is a strong friend for me, I would like it was even STRONGER.

 

Mark Haniford replied on Fri, 2010/03/05 - 11:32am

It was a decent article and made some valid points. Something that wasn't brought up regarding strong vs static typing, is that some older developers substitute strong for static. But as others have stated, the verbosity problem is mostly to do with Java and not static-typing.

Ricky Clarkson replied on Sat, 2010/03/06 - 3:23pm in response to: Claude Lalyre

claudeL, That is incorrect. Groovy is dynamically typed. Witness: int x = "hello";, valid Groovy code, and my favourite demonstration of why I don't use Groovy. I have no idea what Groovy++ does with that.

Oliver Weiler replied on Mon, 2010/03/08 - 6:44am

Disadvantages of Strong typing : More concise and precise, less typing

def nums = [1 .. 9 | step 2];

println(nums); // prints 1, 3, 5, 7, 9

  Not concise enough?

 Closures / Functions

var apply = function(a: Integer, b: Integer) { a + b }
println(apply(10, 20));

apply = function(a: Integer, b: Integer) { a * b }

 

These are some simple JavaFX code snippets just to show that

  • Strongly typed languages can be concise.
  • Can have closure functionality.

 

 

 

 

 

 

 

 

Philippe Lhoste replied on Mon, 2010/03/08 - 9:24am

Osvaldo, a dynamically typed language can be strongly typed, indeed, but that's not the case of JavaScript: it is weakly typed. You can write:

var x = 55;
echo(x + 2);
x = "Foo Bar";
echo(x + 2);

and it will run happily. You can even replace + by * (getting a NaN on the second box).

 trollhorn, your first JavaFX example  is incorrect (just drop the pipe char) and the second doesn't show closure, just function as first-class object, which is already nice. Of course, JavaFX does have closures too. Example:

function GetIDToStringConverter(prefix: String)
{
return function (id: Integer) { "{prefix} {id}" }
}
var GetIDAsString = GetIDToStringConverter("User:");
println(GetIDAsString(422010));
GetIDAsString = GetIDToStringConverter("Customer:");
println(GetIDAsString(201042));

Allen Geer replied on Tue, 2010/03/23 - 9:41pm

I find your post terribly short sighted, and borderline ignorant. Most of your "objections" come from having to type too many characters to define something. Very simply, generic, dynamically typed code works great in situations where the method of input to the code segment severely limits the type of the data coming in. But in situations where you are developing a framework structure, where there is no telling what is putting data into the system, strong typing not only makes it easier for people to understand and quickly utilize your code, but also keeps you from having to write a ridiculous set of invalid-input error handling procedures to handle the languages lack of strong typing. I find this problem rampant in PHP and JavaScript frameworks, where I have to hunt and hunt for what form an input variable is supposed to take. If its strongly typed, then I can infer what form its supposed to take from the type definition. If its not, I have to hunt the internets looking for some stupid example of an array they have passed in. 

Secondly, you don't have to strongly type java at all. Just define all your interfaces with Object return and parameter types. Now you can pass around whatever data you want to whatever function you want... and then guess what you do... the same thing you do in PHP or JavaScript.... you write code to handle the situation where the method has been provided an invalid type of input. Checking to see if my attempt at adding two numbers fails because it returned NaN, or checking what type my input is to make sure it is a number type is the same process.

Your objection to generics is once again an objection to having to type 35 characters vs 20, which is stupid.  If you are really feeling a problem with 15 more characters you should really evaluate the design you've came up with and try to encapsulate all those generic definitions into a more concise one. Or use copy/paste. Java's generic implementation is not poor. You state that java.lang.reflect and generics simply don't mix, which simply is not the case. Perhaps you were looking at the 1.3 javadocs, because java.lang.reflect has all the methods you need to understand the internals of the generics (http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/GenericDeclaration.html).  

And your objection about closures is simply stupid. The notion of a closure which you are describing doesn't make sense in regards to the OOP paradigm. You are referring to a strictly procedural closure, which really provides you with no additional benefit in an OOP language. And you don't have to write your own interface at all. You can do the equivalent of a closure by anonymously implementing the Runnable class, setting member variables of the anonymous class where appropriate. And at the very least, you could extend the runnable interface it takes in an Object parameter and perform a cast to whatever type you are expecting. While that might change the amount of code you have to write by 20-30 characters, it really offers the users nothing in terms of advanced functionality. It's simply a neurotic requirement, providing little to no benefit to the programmer while adding unessecary complexity to the language definition.

 

Anyway, less of you, more of people actually contributing useful information to the world.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.