Regarding Dynamic Typing

Currenty there seems to be a big hype about EcmaScript (JavaScript). Google probably wants to enslave the world with Chrome OS, where the system is not much more than an EcmaScript virtual machine provider (maybe it will support native applications through NaCl, like Android does not only allow Java…), Microsoft wants to reimplement their Windows interface, Qt invented QML, the EcmaScript extension we all know about, providing cool declarative features. Today I want to talk about a fundamental property of EcmaScript and why it just sucks: dynamic typing.

Clarification

First let us clarify the meaning of “dynamic typing”. “Dynamic typing” means that the type of expressions gets checked at runtime, expressions which may have any type are possible. It should not be confused with duck typing, e.g. many types using dynamic typing have a lot of built-in functions relying on specific types (“the frog will not get accepted”), e.g. most functions in PHP’s standard library (expecting string, integer, array or what ever). But for example C++ function templates in etc. provide duck typing (they will accept anything looking like an iterator), or the signatures in old g++ versions provided duck typing. Determining types may happen at compile time (type inference) even with dynamic typing, and of course optimising compilers/interpreters are doing that.

Impact on Development

Let us talk about an argument for dynamic typing: it makes life easier. Actually, that can be right, there are domains where you just do not want to care about such stuff, for example when writing a shell script with few lines of code or when quickly doing some calculations with a computer algebra system. But Typo3, MediaWiki, Windows, Plasma etc. are much more than that. Why do I doubt that dynamic typing makes life easier in those contexts? Because it is error-prone. It is always better when errors get detected at compile time. It is good to fulfill contracts when programming, and they should get verified at compile time, such that they can be easily found and will not annoy the user. A type of contract (not the only one, cf. design by contract) which has been used for long time is the type system. The programmer assures that a variable has a certain type. What happens in dynamically typed languages? You do not have to state the contract, the compiler (or code checker) will usually not be able to check it, it is just in your brain, but of course you will still rely on that contract, the type is something you rely on most of the time when programming, I know that x is an integer when using x for some arithmetics. But you will do mistakes and you get buggy software. That is the fundamental disadvantage when programming, but of course I have to compare it to the advantages of dynamic typing: you can write code quickly and efficiently not mentioning the type everywhere. But there are more proper ways to achieve that: use type inference. The type of a variable will be determined by the compiler when initialising it and you will get an error when you are trying to change the type. That is good because in most cases the type of a variable will not change. And you will get informed about undefined variables (a typo should not cause a runtime error, but in dynamically typed languages it does). For the case that you need a structure allowing different types at the same position there are algebraic data types. With algebraic data types you can state a contract with only few tokens (instead of a nested array/dictionary data structure with a layout which is just implicitly given by the manipulation of it, that does often happen in dynamically typed languages), for variable declaration you only need one token, maybe a single character. That minimalistic overhead in code length is definitely worth it once the software has reached a certain complexity. That threshold is probably not very high, annoying mistakes which could have been avoided with static type checking can already occur in small programs just computing some stuff or something like that.

Performance

Dynamic typing causes big overhead because instructions have to be choosen at runtime based on type information all the time. Of course it is much more complicated to optimise dynamically typed languages, there might be corner cases where the type is not the expected one, but the runtime has to care about it etc. I often read statements like “the performance critical parts are implemented natively” etc., but regarding the amount of applications running using such languages (JavaScript, PHP, Ruby, Python, Lua) we have to state: it is performance critical, PHP is used for more than a preprocessor, QML is used for more than just representing the UI, JavaScript is used for drawing a lot of complex stuff in the browser, Python gets used for scientific computations, and Ruby is establishing new standards regarding overhead (that is not true, Scheme has been that slow before ;), but Ruby allows modifying a lot of stuff at runtime, too). There is reasonable overhead—for abstraction, generalisation, internationalisation etc., but dynamic typing affects nearly any operation when running the program, that is unreasonable and of course it will sum up to significant overhead, although it is simply not needed (and bad for environment ;)).

Special Issues

Regarding extreme flexibility

First of all: in 95% of applications you do not need it, you do not have to modify types at runtime, adding member functions to classes or objects and all that stuff. Sometimes it may be a good way to establish abstraction etc., but in those cases there are usually alternatives: meta-programming can be done at compile time, when manipulating all the types in Ruby they usually could have been manipulated at compile time, too, but Ruby does not support sophisticated compile time meta programming (ML and Template Haskell do, in C++ and D it is kinda limited). Regarding collection of information, debugging etc. using such features: debugging facilities should not influence the performance and cleanness, I am sure by involvement of meta programming you could implement language features allowing that when debugging without neglecting the type system. And of course a lot of flexibility at runtime can be achieved without allowing any type everywhere: dynamic dispatch (including stuff like inheritance, interfaces, signatures and even multi-dispatch), variant types at few places (e.g. QVariant, although I think it is used too often, signals can be implemented in a type safe way, and there are those type safe plugin factories as alternative to QtScript and Kross), signals and slots, aspects etc.

Regarding EcmaScript

You might say that EcmaScript is becoming fast enough because of good compilers and extensions like type safe arrays (e.g. containing only floating points). But EcmaScript will stay EcmaScript, it will keep the downsides of dynamic typing, those type safe arrays are an ugly hack to make it feasible for some specific applications. It is simply lacking a proper type system and it will not get it.

Regarding QML

Using EcmaScript for QtScript was a pragmatic choice, no awesome innovation: there were many web developers knowing about JavaScript. Unfortunately that caused yet another way to integrate scripts and certainly not the most flexible one (cf. my previous blog post), for some reason they did not want to reuse KDE’s innovation (like QtCreator and KDevelop, but that is really a different topic…). QML is based on EcmaScript because QtScript had been based on it before. Dynamic typing is definitely not an inherent property of such declarative UI, most of it could have looked the same with a native implementation based on C++, but also implementations in Ruby or whatever would be easily possible. I have to admit that C++ is not perfect, it does not provide sophisticated meta programming, algebraic types or one-letter type inference (“auto” has four letters ;)), the last one may be a small problem, but overall it is simply not simple enough ;), languages like Scala, D and OCaml have certain problems, too. Hence some of the non-declarative code in QML would have been disproportionately complicated compared to the declarative code. The general approach of declarative UI is certainly good, and now we probably have to accept that it has been implemented using EcmaScript, we can accept it, as long as it is still possible to write Plasmoids using C++ or whatever etc.—obviously that is the case. Thus QML is generally a good development in my opinion, although implementing program logic in it is often not a good idea and although dynamic typing leaves a bitter aftertaste.

I hope you have got my points about dynamic typing. Any opinions?

25 Responses to “Regarding Dynamic Typing”

  1. Ariya Says:

    Modern (and ancient, see Self) JIT compilers, even for JavaScript (just checkout JSC, V8, or SpiderMonkey) has advanced optimization including tracing analysis to inference the object type, which yields in tremendous performance boost.

    And performance must be evaluated with specific use cases. I think you will be hard pressed to find a certain heavy duty processing (but not a superspecial niche) that is extremely slow if it would have been implemented in pure JavaScript. While doing the development, there exists already tools like JSLint that can warn the developers if she mixes up the object type, or keeps changing it to store different types.

    The advantage of the dynamic typing (along with other good features of such a scripting language), in most cases, outruns the tedious edit-compile-cycle in the traditional static environment.

    In short, I ask you to present a case, e.g. a piece of common real-world application logic that is typically found in desktop and mobile apps, which shows the huge performance difference if it is done in C++ vs JavaScript. That would be more insightful, rather then just an outdated judgement of dynamic typing performance penalty.

  2. The User Says:

    @Ariya
    I mentioned both type inference and linters. I am aware of them. But not every type can be inferred, and of course JIT compilers do not have infinite time to predict everything. Would there be statically typed arrays introduced into EcmaScript if the optimiser would be that perfect?

    Could you tell me about the great advantages and good features making it better? Compilers can be very fast. Btw. the main part was not about performance. What are your advantages of dynamic typing?

    And what is special about EcmaScript? I kinda understand people liking Ruby, Scheme or Python, they have special features, their own beauty, but EcmaScript, that is just prototyping+dynamic typing, no outstanding features, no proper type system, no meta programming etc.

    Of course it is hard to find separate implementations in EcmaScript and a different languages of real world programs. But you can try the emscripten examples, they are significantly slower… You can argue that they are automatically generated, but on the other hand LLVM→EcmaScript translation certainly does not use fancy prototyping stuff etc., but operations on statically typed arrays and stuff like that, thus it should be easily optimisable.

  3. Ariya Says:

    You keep pushing the corner cases.

    Please come up with a real-world example of indetermine type in a case where the performance is severely degraded because that. Remember that loops are usually the critical parts of the program (speed wise). And yes, I can make a ridiculously slow loop with JavaScript, as much as I can do it with C++ or Java.

    It is true that JIT compilers do not have infinite time to predict everything. However, by avoiding the need to compile everything beforehand, it can start very fast with a conservative interpreter and optimize the execution on the fly. Doesn’t it come as funny to you how gcc works really really hard to squeeze the performance of your entire application although you just change a variable name and recompile?

    Typed arrays come from the need of WebGL. They may be optimized better by modern JIT compiler. However, remember that WebGL fulfills special nice: graphics-heavy application. Typed arrays can benefit some applications, in terms of performance, but real world applications hardly overlap with the need of that.

    As for ES/JS advantages, let me just mention one: function as first-class citizen. That alone allows the use closure and lambda, which significantly improve the logic flow and source readability.

  4. The User Says:

    There are also incremental compilers, you do not have to tell me that gcc is slow. And it is also caused by the lack of modules in C++.

    In my opinion it is hard to find a fairer comparison than emscripten.

    They may be optimized better by modern JIT compiler.

    If they would be as good as you are saying, they should be able to find it out by themselves and choose an appropriate internal representation.

    Functions as first-class citizen: that is a must-have feature in any modern language and does not depend on the type system. You do not need dynamic typing for it, closures can be efficiently implemented with static typing. Look at D, Scala, Haskell… And of course in a type safe environment it is much less error-prone to handle them, although you do not have to write more code because of type inference.

    I mentioned a lot of downsides of dynamic typing, you mentioned some workarounds, but no advantages.

  5. Johan Ouwerkerk Says:

    You simplify this far too much on the one hand, and you are wrong on the other hand.

    The firs thing to note is that EcmaScript was chosen for Qt based on the fairly simple criteria of: need something that is not compiled, must approach plain Qt in speeds, but must not come with a big VM attached and must be “easily” bolted onto Qt. That pretty much leaves only JavaScript. Or Forth, I suppose.

    The second thing is that dynamic typing is not “slower” because it has to resolve function calls at run time. Not slower than C++ anyways, because that is exactly the same sort of thing which is required for virtual functions or dynamic linking for shared libraries. This, is in fact, the very reason why you need to declare those functions virtual so the compiler can generate instructions to resolve them at run time based on actual type…

    The third thing is that dynamic typing is really quite separate from whether or not it is easy to catch errors: basic Haskell code for instance looks quite a lot like Python code in this regard because neither will need to explicitly define types — in one case it must be inferred from context/constraints and in the other case it is much the same except the crash occurs at runtime instead of failing to compile… The difference here is in tooling support, for Haskell you can’t get around the compiler so you will be notified of these errors. For Python not all editors provide support for inferring the meaning of your code, so not all of them will warn.

    The real difference is in strong typing versus weak/loose typing. This is where there are issues pretty much everywhere you look. In Haskell you often keep scratching your head when you try to use the dot operator because conceptually it fits your model of the program better than the $ operator … to find the compiler vehemently disagreeing about this. This very strict approach makes it easy to catch errors but less easy to write code in it that compiles.

    In C++ there are all sorts of hidden and nasty casting rules, type punning and screen fulls of template errors. This is not helpful either.

    In PHP or Perl everything is accepted and the wrong output generated silently… so you do have to be really on top of things if you are trying to debug. On the other hand, extremely easy to just get something going.

    Onto something actually more noteworthy: JavaScript has something called prototyping. This is why I think it is very, very, good choice for providing a bit of dynamic flair on top of objects exported from heavy duty libraries:

    String.prototype.say = function() {
        alert(this); // assuming that alert pops up a message box
    };
     
    "Hello world!".say(); // pop up a message box saying "Hello world!"

    The feature is a godsend if you are working with arbitrary “backend” objects and need to layer on top of that a common API so your GUI objects can call into that common API and work without modification.

  6. Ariya Says:

    I think you started with your bitter taste towards dynamic typing. I am not even going to try to change that, after all it’s about taste. All I wanted to mention I did it already, i.e. the worries (I disagree if that is called downsides) that dynamic typing masks programming error and slows down the application is not warranted in real-world applications.

    If anyone wants to continue this toward the flame war of C++ vs JS (or static vs dynamic), go head and enjoy it!

  7. ruurd Says:

    You’re right ofcourse. Why? Scripting languages just are not invented to do large scale development. A small tweak on the side, a little wrapper here and there, a bit of representational sugar to make thinks look nice.

    But alas. The trend seems to be to fly of a tangent and develop in the scripting language du jour until one reaches a stage where the point of no return has long been passed.

    Some however learn or have learned the lesson. Have a look at for example Twitter where dynamically typed languages slowly are restricted to where they are at their best – in environments where roundtrip time is important.

    This is the same with a lot of things in our profession – one must choose the tools widely but one must not be afraid to change the tools in use as soon as the situation warrants it.

    Oh. And considering the security question, what base is this in? :-)

  8. The User Says:

    @Ariya
    It is definitely not about C++. And what are the benefits of dynamic typing everywhere? You think explicit contracts are bad for development?

    @Johan Ouwerkerk

    That pretty much leaves only JavaScript. Or Forth, I suppose.

    Why limiting it to a single language? (and you have forgotten Lua I think)

    I know prototyping, but what is the benefit compared to class-based object system? It is more simplistic and dynamic, but also harder to optimise and less expressive.

    Not slower than C++ anyways, because that is exactly the same sort of thing which is required for virtual functions or dynamic linking for shared libraries.

    No, it is not exactly the same thing, dispatching a virtual function call only needs two derefenciations with an offset known at compile time. Lookup for dynamic linking only happens once. How should a lookup with prototypes etc. be as fast?

    in one case it must be inferred from context/constraints and in the other case it is much the same except the crash occurs at runtime instead of failing to compile…

    At runtime you may not notice all corner cases which can be discovered using a static type system. There may be various different stuff in your dictionaries etc. And, seriously, a language should not depend on a good IDE.

    In C++ there are all sorts of hidden and nasty casting rules, type punning and screen fulls of template errors. This is not helpful either.

    Sometimes C++ is not strict enough about implicit casts, it allows casts with loss of precision etc. Long template messages are usually caused because gcc because it does resolve all typedefs and default values, although you are usually not interested, that is not an inherent property of meta programming. In dynamically typed languages it is infeasible to allow implicit casts everywhere, that is really annoying.

    Scripting languages just are not invented to do large scale development.

    Yes, PHP has been created for some preprocessing, JavaScript for some dynamic actions in the browser, not as a universal language or even a universal virtual machine, and Perl was just for some admin-jobs and text-processing.

    Oh. And considering the security question, what base is this in? :D

    Yes, contracts improve security, you cannot infiltrate anything. :D

  9. illissius Says:

    Basically agree, with the caveat that for most people, “static typing” means C++/Java/C#, and C++ gives static typing a bad name. Ugly and verbose code, along with lots of compiler errors, which most of the time don’t even reflect any real flaw in your thinking, just the particularliness of the compiler. After that, Ruby is like a breath of fresh air — concise, expressive, and elegant. But nothing went from “new hotness” to “old and busted” like Ruby did after I discovered Haskell. The same level of conciseness, elegance, and expressivity as Ruby, and you get to say “it compiled, so it probably works” – with a straight face. (You still get lots of compiler errors, but most of the time they inspire the reaction, “I’m an idiot”, rather than “just friggin compile already”.) As a basic smell test, no statically typed language which implicitly allows its object types to be null without any kind of representation in the type system is really deserving of the name.

  10. Richard Dale Says:

    I find this post a bit annoying to be quite honest, because you sound as if you are handing down your ‘tablets of stone’ to us lesser mortals. I believe in using the best language for the job, and I agree that often C++ is indeed the best language for the job.

    However, your blog has something of a religious pro-C++ flavour (hence my tablets of stone comIment above). For example:

    .. Google probably wants to enslave the world with Chrome OS

    ..you just do not want to care about such stuff, for example when writing a shell script with few lines of code or when quickly doing some calculations with a computer algebra system

    You seem to think that because C++ has that wonderful ‘static typing’ magic that as soon as you can get a C++ program compiled (not always easy at all if you are using templates), then it will ‘just work’. Of course in reality you need to be writing the same unit tests for C++ that you would also be writing for Ruby or Javascript. And the effort involved in writing C++ unit tests is much the same as for dynamic languages.

    You ignore the fact that large systems have been coded in Python, Ruby, Smalltalk or Javascript and they are no harder to maintain, less efficient or more error prone that if they had been written in Java or C++. If you are so correct, how come the actual experience of those who have developed systems with dynamic languages don’t agree with your assertions?

    The ‘Javascript is less efficient’ canard also irritates, because the latest Javascipt VMs are blindingly fast. If the same level of effort was put into a Ruby or Python VM I’m sure they would be as fast as Javascript. A dynamic language can give you more information at runtime to help with optimizing a JIT compiler that a batch language like C++.

    As other people replying to your blog has said this is all a matter of taste, and I wouldn’t have a problem, if you were taking care to say that the views in the blog were your own and others were free to differ. But that is not what the wording looks like. Sorry.

  11. Afief Says:

    So dynamic typing has problems, I’m pretty sure we all agree on that(and what I see in the discussion is mostly “I prefer having these problems to having these problems.”) But isn’t the point of javascript in QML basically to do simple logic and/or update the GUI. All the heavy lifting can still be done in C++ if the developer finds it appropriate.

    Am I missing something?

  12. The User Says:

    However, your blog has something of a religious pro-C++ flavour (hence my tablets of stone comIment above).

    It was not about C++. I know that C++ has many flaws. The main issue about Chrome OS is not the language used (though EcmaScript is kinda restricted) and that was just a voluntarily lapidary introduction.

    You ignore the fact that large systems have been coded in Python, Ruby, Smalltalk or Javascript and they are no harder to maintain, less efficient or more error prone that if they had been written in Java or C++.

    PHP, Rails and Zope servers are definitely consuming a lot of ressources. There are large projects written in Cobol, Fortran or Assembler, too…

    because the latest Javascipt VMs are blindingly fast.

    If the same level of effort was put into a Ruby or Python VM I’m sure they would be as fast as Javascript.

    Well, there are conceptual differences, Ruby is probably extraordanarily hard to optimise because of all the runtime manipulation.

    If you are so correct, how come the actual experience of those who have developed systems with dynamic languages don’t agree with your assertions?

    Well, nobody has yet really argued against my statements about code quality etc. And there can be various reasons: good people, eloquent coding standards, unit tests everywhere (in statically typed languages you do not have to add that many tests, because the program gets proven to be well-typed), luck, excessive usage of tools… I did not say that any project has to surrender just because it is using dynamic types. I did say that it has big disadvantages while not making writing code easier.

    if you were taking care to say that the views in the blog were your own and others were free to differ. But that is not what the wording looks like.

    I am really tired of such accusations, it is obvious that other people have different opinions and I do not agree with them, what is the matter?

    A dynamic language can give you more information at runtime to help with optimizing a JIT compiler that a batch language like C++.

    That has nothing to do with dynamic typing. Have you ever done a profiling launch? And I am sure you have heard about LLVM, what would be about some effort for implementing idle time optimisations in LLVM, I think that would be much better than repeating the stuff from V8 for Ruby or Python. I am definitely not against JIT compilers…

    But isn’t the point of javascript in QML basically to do simple logic and/or update the GUI. All the heavy lifting can still be done in C++ if the developer finds it appropriate.

    Declarative UI does not need dynamic typing, it is kinda sad that in Qt new features are limited to EcmaScript…

  13. Richard Dale Says:

    if you were taking care to say that the views in the blog were your own and others were free to differ. But that is not what the wording looks like.

    I am really tired of such accusations, it is obvious that other people have different opinions and I do not agree with them, what is the matter?

    If you are getting regular complaints about your blog, please don’t format your blog like it is some kind of ‘man’ entry. It isn’t, it is your personal opinions. It seems pretty obvious to me what the previous criticisms of your blog were about. That said I am personally very interested in static vs dynamic language discussions, but please don’t post blogs where you purport to already have the definitive answer.

  14. The User Says:

    “Regularly” is not correct, some time ago some people complained about something similiar (should clarify that it was about personal thoughts, very annoying), but the post was not formulated as a definitive answer. That was a general statement, I am also tired about reading it somewhere else. I have listed advantages and disadvantages and talked about alternatives and stated a clear judgement, because so far that is my result of my considerations about that issue, I have also talked to other people before… It should be obvious for everybody that this is no exact science, it is an inherent property of the topic that you can disagree with something, thus I will not write “that is just my opinion” or anything like that.. I am interested in points for dynamic typing, feel free to state specific benefits I did not consider. So far the discussion has been kinda boring, because there were just statements like “it is not that bad”, but nobody has talked about advantages of dynamic typing.

  15. incunabulum Says:

    The User, personally i can only wholeheartedly agree with respect to your opinion regarding static vs. dynamic typing.

    While I am by far no professional software developer I have done quite my share of programming in java, c++ and python. In all three languages, projects with more than 50k lines of code were developed and maintained in a team over a longer period of time. And over time, static typing paid really off. Especially in maintenance mode, i.e. when you are not really familiar with every aspect your code anymore, static typing can really help to actually make sure that your change is compatible with the complete system and that you have done really all the changes required throughout your code base. It still has to do what you want, though :-)

    With dynamic typing, it is back to the run, test, change, rerun, test again cycle. And – especially if a GUI needs to be tested, this needs a lot of time and can use up quite a lot of your nerves. And you need to remember all the code paths to test. Unlikely. Or – as mentioned in the comments above – write an insane (sorry!) amount of tests to test each and every aspect of every function in a dynamically typed language. But, well, I would never think about writing a test function for something like a function which does a=a+1. But for a dynamically types language I would as there could be a typo in the function’s implementation which can lead to a crash. How about you?

  16. Johan Ouwerkerk Says:

    Why limiting it to a single language? (and you have forgotten Lua I think)

    I know prototyping, but what is the benefit compared to class-based object system? It is more simplistic and dynamic, but also harder to optimise and less expressive.

    Well the great benefit is that you can inject behaviour you need for objects that you did not create, either on a per object basis or by using prototyping on its type/class for all such objects in existence. If you look at the example I provided, that say() function works for *all* strings thereafter.

    No, it is not exactly the same thing, dispatching a virtual function call only needs two derefenciations with an offset known at compile time. Lookup for dynamic linking only happens once. How should a lookup with prototypes etc. be as fast?

    Actually it is highly similar if not same. The difference being that with virtual functions the lookup table (vtable) of the object is located with the data, but conceptually the thing you do with JavaScript is program the vtable directly. String.prototype.say is conceptually equivalent to instructing the VM to create a function called say for the String vtable. This means, and I’m sure the actual reality will differ, that prototyping is roughly like entering into the actual compiler/linker and adjusting the executable code on the fly.

    Incidentally with JavaScript you can do similar neat things. For instance singletons in Java can be done reasonably convenient using Enums with a single instance member:

    public enum SingletonClass {
        INSTANCE(); /*  the Java VM will enforce that there is only one SingletonClass object ever, namely SingletonClass.INSTANCE. */
    }

    But in JavaScript you could do this instead:

    function getSingleton() {
        var single = code_to_compute_singleton();
        /* modify the function so it simply returns the pre-computed single object */
        getSingleton = function() {
            return single;
        };
        return getSingleton();
    }

    As to the problem with casts: the point is that in C++ they happen when you least expect them. Or they don’t happen when you do. C++ is not a logical language except for those who have been conditioned to think in C++.

    The overarching problem is that there is no clear right way to do things, and JavaScript happens to offer a few features that make it very useful for working with seemingly static and immutable environments that few other languages do.

    The fact that JavaScript is nicely familiar for hordes of developers is really a bonus but not the sole reason for going with JavaScript — if that were the case Python could have been chosen just the same.

  17. The User Says:

    @incunabulum
    What about me? :D I have also had good experiences with static typesystems and bad experiences with dynamic typing, both when writing significant amounts of code in a team (it was PHP), but even when just writing some small stuff by myself involving a bit complex computations (Ruby most of the time). Or what did you want to know about?

    The fact that JavaScript is nicely familiar for hordes of developers is really a bonus but not the sole reason for going with JavaScript — if that were the case Python could have been chosen just the same.

    First of all that does not explain why any single language had to be choosen.

    Well the great benefit is that you can inject behaviour you need for objects that you did not create, either on a per object basis or by using prototyping on its type/class for all such objects in existence. If you look at the example I provided, that say() function works for *all* strings thereafter.

    When should it be useful? No function can rely on the presence of the method unless it is always present for certain objects, and then the method could have added at compile time (I am not saying C++ supports that). Changing existing methods is also possible in C++ style languages (inheritance, or you can change the vtable).

    Actually it is highly similar if not same.

    Both are dispatches, but the performance if different, if it is possible to swap prototypes etc. it is not possible to have a fixed layout for fast lookups like it is possible with virtual functions.

    As to the problem with casts: the point is that in C++ they happen when you least expect them. Or they don’t happen when you do. C++ is not a logical language except for those who have been conditioned to think in C++.

    The rules are not perfect, stuff like casting between signed and unsigned or between float and int are too unsafe, but sometimes it is very convenient to have such features, casting short to int or when handling strings (“bla” + 123.to_s in Ruby is annoying), the best thing about it: it is a general concept, not just a special feature for some built in types, but (nearly) completely customisable. In Haskell it would make type inference amiguous in many cases, in dynamically typed languages coercions would have to be looked up at runtime very often, which would be infeasible. The singleton implementation is a demonstration of closures, it would look the same in D or Scala while assuring a specific type.

  18. Johan Ouwerkerk Says:

    First of all that does not explain why any single language had to be choosen.

    Well no, not in the sense of that one must choose between language, but in the sense that the people who decided QML was a good idea they certainly needed some language to actually allow it to be used in. They could have chosen any language of course, but settled for JavaScript which was explained well enough when it was announced.

    The singleton implementation is a demonstration of closures, it would look the same in D or Scala while assuring a specific type.

    The closure happens to be irrelevant. The relevant bit is where the function itself is reprogrammed to be the closure, i.e. the assignment of a new function to the function itself in its own block scope.

    When should it be useful? No function can rely on the presence of the method unless it is always present for certain objects, and then the method could have added at compile time

    It should be useful if you happen to be working with backend systems/libraries/objects that *you* cannot change. Assume that you write a generic media player application. You might have a gallery type of UI, where the user can click on thumbnails to go to some item.

    Now these files might have all sorts of mime types, and you might rely on all sorts of backends to play them (for instance one thing could be played through VLC, the other through mplayer, or whatever), yet others might simply not expose any play functionality at all.

    Prototyping here is useful here because as described before you can maintain a JavaScript shim around the objects exposed from the underlying libs so that the specific behaviour of the objects is normalised if accessed through the shim API. A typical example here is seeking. Some players might want an absolute number of miliseconds, some might want a percent. As a backend developer you know this to be the case, so you write code which converts seconds into percents or percents into seconds based on track length, and the common shim seek() function works. So the interface designer who wrote the nifty UI merely needs to know how the seek() function works and does not need to know about the differences between VLC and mplayer and whatever else the application might use under the hood.

    Now you said, but one can fix this in advance, simply add the necessary code before/at compile time. However my point is that the whole idea of using JavaScript in the first place is to let people assemble their applications from ready made components, and this goes with the caveat that they do not have full control over them.

    So patching up at run time like that is the only sane thing to do if you cannot expect the users to use your own home brew version of popular software packages and/or if upstream is not interested in changing behaviour for the sake of your application.

  19. The User Says:

    With Phonon that is pluggable at runtime, too, it is flexible, written in C++, and typesafe with well-defined interfaces…

    The relevant bit is where the function itself is reprogrammed to be the closure, i.e. the assignment of a new function to the function itself in its own block scope.

    The type does not get changed, you do not need dynamic typing for it.

    PS:
    I am not a D expert, so had to apply trial&error, but that one works:

    import std.stdio;
    
    void main(string args[])
    {
      string delegate() singletonString;
      singletonString = ()
      {
        string value = "Hello, World!";
        singletonString =  ()
        {
          return value;
        };
        return singletonString();
      };
      writeln(singletonString());
      writeln(cast(void*)singletonString());
      writeln(singletonString());
      writeln(cast(void*)singletonString());
    }
  20. Anonymous Says:

    I don’t understand how QML is “good development” especially after text above that is bashing JavaScript. QML is only really useful to have somewhat changeable UIs, nothing more.

  21. shamaz Says:

    your blog is really annoying. You are polluting planetkde with all your nonsense.

  22. Trurl Says:

    @shamaz: There are very good reasons why type systems were developed, so criticizing the use of dynamic typing in software engineering is reasonable.

    @all: I think the problem is not necessarily dynamic typing itself, but that it is not always used correctly. Some people say that dynamic typing makes code shorter and easier to write (the same argument often heard for functional programming), and that short code is a good thing. Therefore, dynamic typing must be good especially when it leads to shorter code. But this is, at least in this generality, *not* the case: code quality is not a matter of code length. Yes, you are right, short code is often a consequence if one follows other code quality criteria, but shortness is not a code quality criterion by itself! Code may indeed become longer by following code quality rules. It depends, so you have to keep your eyes open.

    There is a very simple rule when to use dynamic typing. It reads: Dynamic typing may be used when static typing is not implicated by the project’s complexity. In all other cases, or if in doubt, static typing is the right choice.

    And there is also a simple heuristic that may help: If you choose static typing, this choice can never be wrong, at the worst unnecessary. If you choose dynamic typing, this choice could turn out to be wrong.

  23. The User Says:

    Well no, not in the sense of that one must choose between language, but in the sense that the people who decided QML was a good idea they certainly needed some language to actually allow it to be used in. They could have chosen any language of course, but settled for JavaScript which was explained well enough when it was announced.

    I was mainly talking about QtScript. For that purpose you definitely do not have to choose a single language, and if Qt would not have been focused on EcmaScript with QtScript it may be easier today to adopt the declarative concepts to other languages.

    @Anonymous
    Declarative GUI has been a good idea.

    @shamaz
    Somebody has just polluted the comments in my blog with unfounded criticism, but my criticism in my blog is not unfounded and obviously there are also people sharing my points of view.

  24. Anonymous Says:

    Personally, “declarative” and tied to JavaScript seems like a misnomer to me.

  25. The User Says:

    @Anonymous
    What do you mean? I do not understand the meaning of your sentence. You mean “declarative” implies being tied to JavaScript? Declarative style would be possible on top of other languages as well, QML is a language extension, other languages could be extended in the same manner.

Leave a Reply

XHTML: Use <blockquote cite="name"> for quotations, <pre lang="text    ∨ cpp-qt ∨ cpp ∨ bash ∨ other language"> for code, [latex] for formulas and <em> for em. Contact me if the comment does not get published, it may have accidentally been marked as spam.

Anti-Spam Quiz: