July 14, 2013

Static vs Dynamic Types

So, now that I have been programming in a dynamically typed lanugauge, I have seen the benefit of both types of languages. Let’s go over some of them.

The biggest difference that I noticed between JavaScript and C # was the idea of loosely typed code. The problem with typing is the ceremony of describing one’s type. This creates upfront developer time. For example:

 //C# public string DoSomething(int number) { string result = ""; for(int i = 0; i < number; i ++) { result += i.ToString(); } return result; } 

Now, let's see it JavaScriptified :

 //JavaScript function DoSomething(number) { var result = ""; for(var i = 0; i < number; i++) { result += i + " "; } return result; } 

Looking at it, C# has a lot more description of types going on, and javascript does not. This causes C#'s compiler to allocate resources and become faster at allocating memory. The other issue with the code is that the type in JavaScript does not convey what to pass into the function. I could very easily passed in a string instead of a number and deployed the code. The compiler on C# side would have thrown an error saying not to do that. But there has to be a reason that JavaScript is used, right?

what if we transform that parameter from number, to an object? This would complicate C#'s code extensively. On the JavaScript side, we could just call object properties, as if we knew what the object is as a parameter. This gets us back to the idea of do we want to take care of this at run time, or compile time? If run time, then make sure that naming and comments of your API are clearly marked. This will limit misuse of passing objects into the wrong function. Even better yet, CoffeeScript and TypeScript are coming on the scene helping us compile better JavaScript code to avoid the runtime errors caused by us. This doesn't mean that we should drop C#, because the compiler is still there optimizing code. Instead we should look at the solution, as always, to find the best language type to use.

My feelings are that if you are consistantly changing code and it requires developer time, dynamic programming langugages offer the flexiblity, so long as it does not have to be blazing fast. Now, if you are building a product and speed for your client is concern, as well as, compile time mistake catching, use some C#. At the end of the day, I think the internet has it right though, our client pages (which change consistantly), are JavaScript, and our server side technologies are generally fast compiled systems.