JavaScript Jems - Objects Are Anonymous Singletons |
Written by Mike James | |||||
Monday, 05 February 2024 | |||||
Page 4 of 4
Is Strong Typing Bad for You?Strong typing is a big restriction on how you work with objects and its only payback is that you can specify in your code what methods and properties an object has. Notice, however, that this only works if the object's type is known at compile time, and if its type is known at compile time then a compiler could check on what methods and properties the object has without strong typing. In many cases strong typing can be thought of as "active documentation" where you are forced to say what objects can be used in an operation - usually a function call. Programmers generally don't like writing documentation and having the language itself provide some seems like a good idea but it leads to documentation like: int sum(int, int) which is fine when it is obvious what sum is doing to the int, int to give int but this is often not the case. The magic thinking of "type-safe" programming has become the central dogma of object-oriented programming and yet it's rarely put to the test. All too often you will hear "but that's not type-safe" or "there has to be a type-safe way of doing that" without any explanation of what this means exactly and without any cost benefit analysis. There are benefits, but there really are costs. JavaScript's approach to objects is simple, direct and just as manageable, as long as you take the time to test, comment and document your code. Of course, many programmers don't and this is the one big claimed advantage of strong typing - it forces you use to a minimal level of description. In most cases it is enough to think of every JavaScript object as a singleton that might have the same properties and methods as other objects. When you create a point object then you have an expectation that it is going to have an x and y property and so on. If you use an object factory or a constructor then these expectations are made clear. If you use a prototype object for the object's methods then the object's intent is even clearer. So how do you work safely without type safety?
JavaScript programmers have to come to terms with the idea that the objects that they work with are dynamic, singletons and anonymous. Yes, it does take a little more discipline to write good quality code, but not much. The payoff is that prototyping is much easier and faster and you are spared all of the difficulties of strong typing and single inheritance type hierarchies. While not widely recognized this simplicity is another jem. Now available as a book from your local Amazon.JavaScript Jems:
|
|||||
Last Updated ( Monday, 05 February 2024 ) |