-
Intro
In 2011 I was at my first hackathon event. I was very excited, this great successful company was coming to our country and hosting a hackathon! The company was Yahoo!, I know, things don't look so shiny and bright today but it was a big deal back then.
During that event I developed (together with some friends) a fun little snake multiplayer game which, like all hackathon by-products, was promptly abandoned the day after.
The game was written in Node.js, and it was the first time I was writing backend JS, even though I was a true enthusiast back then.
A couple of years later I wanted to revisit the game just to see how bad it really was. I, unfortunately, had an issue: we had never versioned the packages, so everything was outdated and nothing worked. Changes from one version to the next tended to be bigger. I've decided that it was time to rebuild it, just for fun.
The refactor
It was the end of 2015, the Paris agreement was going to stop pollution, Volkswagen was found guilty of cheating the pollutions emissions tests, and I was refactoring "Tequila worms".
Node.js was no longer a novelty but a well established technology, it started supporting alternatives to JS, or should I say EcmaScript. Some of the main options were TypeScript and CoffeeScript.
While TypeScript offered static types which allowed it to find some bugs at compilation instead of runtime, CoffeeScript had a much more "code" orientated approach. CoffeeScript allowed for a simpler and nicer syntax. I agree, it was a bit confusing at first, but it looked great!
The decision was made, the backend will be built in CoffeeScript, it was an obviously better choice than TypeScript.
For the frontend there were several options, but I was not going to use jQuery as there were all these new shiny frameworks available. The question was: should I use React or Angular?
I strongly believed that a frontend library should not use backend for complication. Angular with its version 1, which denoted stability was a favorite! It had a stable version, so it wasn't going to change very soon, it had a good community behind it, and it was built by Google!
React on the other hand wasn't that popular. It also needed backend to compile, which is kind of weird if you think about it, it was build by Facebook, and had a very different approach than the more popular MVC.
Angular (version 1) and CoffeeScript were the winners! I can say that it was a pleasure refactoring this silly game and, above all, I was able to use these cutting edge technologies, making the project future-proof!
You can find the end result here: https://github.com/claudiu-persoiu/tequila-worms/
8 years later
The Paris agreement didn't really change the world as radically as we needed it to, Volkswagen is making electrical and hybrid cars now, and my app doesn't look like state of the art anymore.
As Node.js has matured, its dependencies also become increasingly more complex and in need of constant attention.
On the other hand, Angular was completely refactored in version 2 and my dream of building frontend without the need for backend is becoming a more literal dream.
CoffeeScript script was slowly taken over by TypeScript, and is now closer to a piece of history for enthusiasts then a go-to language.
On CoffeeScript's Wikipedia page, under "Adoption", there's a phrase that describes very well what has become of it:
On September 13, 2012, Dropbox announced that their browser-side code base had been rewritten from JavaScript to CoffeeScript, however it was migrated to TypeScript in 2017.
Conclusion
While Node.js was the only good pick in the project stack, the rest of them only prove that you should not take technical advice from people on the Internet, in this particularly case me, I was just so far off...
On the other hand, none of the technologies were a bad decision at the time, and building frontend without the need of backend wasn't the eccentric desire it may seem today.
CoffeeScript was just unlucky, while it made the syntax nicer, it made it a bit harder for people coming from C family languages to understand it.
While the TypeScript syntax is not nicer, it does help with static type checking.
I guess the main takeaways of this story are that there's no future-proof when you rely on frameworks and that you shouldn't trust anyone's predictions, especially not mine.
--
-
This is a retrospective of the year that has just ended.
In case anybody is still wandering, no, PHP 6 didn’t come out and it will probably not come out any time soon.
Why is it relevant? Since I started this blog, at the end of each year I had a post related to PHP 6 and the fact that it wasn’t released. In 2008 it was a popular question, but nobody is wondering about that anymore, and so I will close this subject now. Let’s return to the year that has just ended.
Close to the middle of the year, the version PHP 5.5 was released, bringing features like: finally , generators and many other enhancements.
Like in 5.4, these are not defining features for the language. In this new version, there are functionalities that can be easily replaced, but if present, they are welcome.
Even though PHP is proving very dynamic lately, I think this year the main keywords were HTML5 and JavaScript.
HTML5 is seeing a lot of improvements and older components begin to have more momentum. The companies are beginning to invest in games that work in the browser using WebGL. Even older games are getting ported to the platform, using technologies like asm.js.
And, because I’ve brought games into the subject, it seems very interesting to me how only 5-7 years ago the games built with JavaScript were relatively simplistic, and now they can be compared with the ones from PCs and consoles.
I think the web revolution, which many were expecting, is taking shape. Finally the Web is a platform in the true meaning and JavaScript a language truly appreciated.
The success is due to all sides, it is not only about ECMA or only about browser manufactures, now it is truly dynamic. The Web revolution is in full blow!
When it comes to backend, the spotlight was on Node.js. It is becoming an important player on the market. New frameworks have appeared and it isn’t a platform mainly used by hackers eager to explore new technologies anymore, but also by large companies, like PayPal, LinkedIn and Yahoo, adding a vote of confidence to it. I think Node.js is finding its place and a niche in the market, and, as a JavaScript fan, I can only be happy.
An advantage of Node.js is that you don’t have to take into consideration different JavaScript versions, like in the browser. It allows the use of the latest features from ECMA freely, an environment where you can develop JavaScript with not headaches.
Technically speaking, it was a very interesting year for web development.
Finally, I want to wish you all an extraordinary 2014!
-
Note: Titanium and PhoneGap are a couple of platforms for developing hybrid applications for mobile. These platforms are not written in the programming language that is native to the phone, but they can be distributed on a verity of mobile platforms.
Recently I’ve published on Github the newest and most extraordinary quizzing platform, named Just-Quizzing. I’ve build it for personal use, but because a few colleagues found it useful, I made it public.
In the initial version, for publishing the application to my Android phone, I used SL4A. I needed a way to use the application when I was on the move and didn’t have Internet access. Unfortunately it didn’t have automatic update for the quizzes. I’ve hoped that with time SL4A will have a clearer path, but the platform lost its initial momentum and I decided to write a mobile app.
I had to choose between PhoneGap and Titanium. In the past I’ve used PhoneGap because the app size was too big in Titanium, but I wanted to give it another go. In 2011, when I first wrote about Titanium, the initial app size was about 4M. Today it doesn’t seem that big, even though it isn’t small.
The perspective will be mostly about Android, even though the app was built to work also on iPhone.
I used SDK 3.1.3, without the Alloy framework.
Alloy has it’s own learning curb and I wanted to avoid it. The prupose of the application was to be a portable version for the quizzes from the server and I didn’t want to make a big time investment.
The total development time was a little more than a week.
First impression
Things don’t work as you expect them to, there isn’t a lot of flexibility. From the total allocated time, more then a quarter I was trying to do a “flyout menu”, like in applications such as: Facebook, Google Plus and Youtube. It was a total disaster! The only options that seemed to work were using an external module or using Alloy widgets.
It seems like when converting relative coordinates, where the user touched the current element, to the general coordinates on the screen there is a big discrepancy and it is impossible to do a sliding menu effect in a decent manner. In the end I totally abandoned this effect.
The speed is not that good when it comes to rendering elements. To be honest, I was expecting a better speed. There are some tricks that help, like pre-rendering the views before displaying them, but for this you must guess what the user will do next, which is not always possible.
Another thing that bothered me was that when the menu button is pressed on Android you can’t take a particular action, let’s say open the side menu that I’ve mentioned before. In PhoneGap for instance, no menu is opened, it must be built-using HTML from the ground up.
When Titanium came out, they were stating that you could develop once and distribute to multiple platforms. Now I was surprised to find that the approach had changed. In the Kitchen Sink, the application that showcases the features of the platform, each platform type initializes the application in it’s own file. One of the reasons is that the design is done dynamically if you are not using Alloy, not trough layout files.
One of the first things that I tried with Titanium was to see the size of a “Hello World” app. Packed, the application has about 8.5M, installed on the phone, it takes up about 16M. I don’t know what you think about that, but for me it is a lot! What is strange is that my final app occupies about 8.4M packed and installed about 16M, almost identical to the original application. The reason is simple, the images replaced by me are a few kb smaller, resulting in an application a little smaller than the one that I started with.
Why does a Titanium application take up so much space?
I had to do some searching before finding the answer. In 2011, when I first tried to research, I only found that all the libraries, needed or not, are packed inside and for this reason it takes up so much space. This wasn’t the cause! Meanwhile, I found the real reason. An application runs a “bridge” between Android and JavaScript. The source code is not “compiled”, as was the initial belief, but just interpreted.
The JavaScript code is interpreted using one of the available engines in the app (V8 and Rhino) and it calls other components that build the native graphing elements.
The issue is with the engines. They are quite big and are packed in every application. And, as if they weren’t large enough, there are 3 of them, each with its’ own purpose:
- V8 – for newer Android version (after Gingerbread 2.3);
- Rhino – for older Android versions (before Gingerbread 2.3);
- x86 – for Intel processors.
These 3 engines occupy a total of 19M, unpacked on my computer. Thus, without eliminating some of them, we can’t get the app size to decrease.
One way Appcelerator is trying to tackle this size issue is to give up Rhino, breaking this way compatibility with older Android versions.
Community
There is a very active community. On the forums and Q/A platforms it’s full of questions and answers! I must admit that I was impressed in this aspect. Some questions are relatively old, even from 3 years ago.
Learning curb
For a week and almost a half, out of which almost a quarter I searched how to do a view moving effect, which in the end didn’t work, I must say it went pretty fast!
I must admit, I’ve played with it 3-4 years ago for a few days and I remembered a few things, like elements of type window, view and label.
The fact that I was able to find answers fast on questions about Stackoverflow, gathered in a few years, but also that the documentation is pretty well organized, helped a lot.
Also on Youtube there are some useful tutorials.
Development environment
In the first versions there wasn’t an IDE, the applications were written with an editor of choice, then packaged and tested using the platform.
Now there is an IDE based on Eclipse. The name is Titanium Studio. It has a pretty nice autocomplete, which helps in a lot of cases. It also has some drawbacks, like in my case sometimes the syntax highlight didn’t work, without any clue were the problem was. Also, project management seems a little strange and it had some issues with import and export of the projects.
There isn’t a default visual tool for editing elements in the page. Both Xcode and ADT allow for editing elements with drag & drop. It turns out there are tools for this, but they are not free.
Emulators are not very configurable. The good part is that you don’t have to worry, you select the operating system and display type and Titanium will automatically configure an emulator. The bad part is that I might wish for a clearer resource management.
Another disadvantage is that sometimes the application will crash before the emulator starts and if you try again it will try to start a new emulator without any luck, case in which the emulator has to be closed. Run Project clean and try again, careful not to miss the moment when the screen can be unlocked, or the scenario will repeat.
For iPhone logs do not work when it comes to OS X Mavericks.
Good parts
It is easy to learn.
The documentation is well done and where something is not clear, surely somebody asked the question before.
There is a fairly large community.
The IDE is easy to use.
It’s easy to see what is possible to achieve with the Kitchen Sink app.
The app doesn’t look like a web page in a WebView!
Bad parts
The app size is quite big (16M on the phone).
The graphical elements are only a subset of the platform.
It isn’t very fast, because the code is interpreted and not compiled, to be able to interact directly with the OS.
There isn’t a visual editor.
There are some issues on integration with emulators, both for Android and iPhone.
Conclusion
If you are a JavaScript connoisseur and you need an application fast and also want to have native graphical elements, then probably Titanium is for you.
If you want performance, probably you need to look for something else.
I don’t have enough experience with the Android SDK to be able to build this application in the timeframe I had available, this was my compromise.
To be honest, I’m not sure wether PhoneGap was a better option or not, speaking for my case. Today there are a lot of JavaScript libraries out there built especially to emulate native graphical elements into a PhoneGap application. The difference is not necessarily visible and, in the end, maybe sometimes the app doesn’t really have to look like a standard app, maybe a completely different interface is more appropriate.
-
The notion of closure in PHP, even though it appeared in PHP 5.3, as I’ve said before on my blog, it was properly done only in 5.4.
Wikipedia tells us:
In computer science, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables) of that function.
In PHP this isn’t a very popular concept or very well-known. It is often mistaken for Anonymous Functions. But in functional programming languages it is very popular, because they really need it!
Scheme
When Brendan Eich designed JavaScript, relied on the Scheme language and ended up doing an implementation of this language with a C syntax. The C syntax was and is a lot more popular, and back then (1995) the Java programming language was very “fashionable”.
The Scheme syntax is similar to Lisp, in the sens that is using parenthesis abound expressions in order to execute them. The operators are defined as functions and just like them, there must be placed left of the parenthesis.
Let’s take an Scheme closure example:
1(define (make-counter) 2 (let ((count (begin 3 (display "run parent function and return 0") 4 ))) 5 (lambda () 6 (set! count (+ count 1)) 7 (begin 8 (display "inside child function ") 9 count))))
The function is setting a “count” variable, with the value 0 and displays “run parent function and return 0”, then returns another lambda function, that is incrementing the variable defined in the main function and then displays “inside child function”.
I’m storing the resulting function in a variable in order to later run it multiple times:
1> (define counter (make-counter)) 2run parent function and return 0 3> (counter) 4inside child function 1 5> (counter) 6inside child function 2
In other words, each time I’m calling (make-counter), it will return a new function that has access to the environment at the time at which it was created. If it looks strange because of the syntax, I promise that it will fell a lot more natural in JavaScript.
This concept is very interesting for encapsulation. The environment from the time when the parent function was been executed can be encapsulated, and later it can be used without worrying that it was changed by external causes.
For the functional programming languages this is a very interesting concept. Yet when it comes to object orientated languages, the concept seems almost useless, because objects also have the purpose of encapsulation.
JavaScript
From the beginning JavaScript was a hybrid, a functional programming language, object orientated, with prototype based inheritance. And if this wasn’t enough, the syntax was taken from Java (C).
JavaScript didn’t inherited a lot from Scheme, but it did inherit the closure concept.
A reason why there was a need for closures in Scheme is that that if a function is not finding a variable in its environment, it will search for it in its container’s environment. Let’s take an example:
1(define x 1) 2(define (add-in-env y) (+ x y))
If we call add-in-env with 2:
1(add-in-env 2) -> 3
It looks just as ambiguous as in JavaScript, but is not exactly like that. In Scheme to do mutation is not that easy, simple and transparent, so an subsequent operation of:
1(define x 2)
will result in an error.
In JavaScript resulted a hybrid. Mutation is permitted, but the notion of searching a variable in the current environment remained:
1var x = 1; 2var add_in_env = function (y) { 3 return x + y; 4} 5 6add_in_env(2); // returns 3
Up to this point is ok, but for:
1x = 2; 2add_in_env(2); // returns 4
For this case, things can get out of hand very easy:
But, in order to solve the issue, we can just define a variable in the environment that will finish execution (will close):
1var make_counter = function () { 2 console.log("run parent function and set counter to 0") 3 var count = 0; 4 5 return function () { 6 count = count + 1; 7 console.log("inside child function"); 8 return count; 9 } 10} 11 12var counter = make_counter(); 13console.log(counter()); 14console.log(counter()); 15 16var counter2 = make_counter(); 17console.log(counter2()); 18console.log(counter()); 19console.log(counter2());
The output will be:
1run parent function and set counter to 0 2inside child function 31 4inside child function 52 6run parent function and set counter to 0 7inside child function 81 9inside child function 103 11inside child function 122
Even though the main function finished executing, the environment inside it is kept as a closure for the function that was returned. Only when there aren’t any more references to the sub-function the memory allocated for the closure will also be deallocated.
Even though JavaScript has objects, it doesn’t have private methods. An approach is to add a “_” (underscore) in front of the function name and consider it private. From my point is like asking the developers that will later use the code to consider this function private. Of course this is not very consistent.
Let’s take an example:
1var obj = { 2 _secretFunction : function (key) { console.log(‘do secret ’ + key) }, 3 doStuff : function (key) { this._secretFunction(key) } 4} 5 6obj.doStuff(‘stuff’); // do secret stuff
It seems that there is a public method “doStuff” and a private one “_secretFunction”. Nevertheless you can not prevent a user from calling “_secretFunction” or even worse, to modify it:
1obj._secretFunction = function (key) { console.log('new secret ' + key); } 2 3obj.doStuff('stuff'); // new secret stuff
If we want to hide the function, and make this obvious for everybody, again, we can use closures:
1var obj = (function () { 2 var secretFunction = function (key) { console.log(‘do secret ’ + key) } 3 4 return { 5 doStuff : function (key) { 6 secretFunction(key) 7 } 8 } 9})(); 10 11obj.doStuff(‘stuff’); // do secret stuff
Because the parent function was not stored but rather immediately executed, basically the space in which secretFunction was defined has already finished its execution, encapsulating the logic. The object returned can call the function because it was defined in the same environment as the object.
Looks complicated at first, but is really very easy when you understand the concept.
And then it was… PHP
PHP includes a lot of different options. It was originally developed as a Perl framework, later the engine was rewritten in C.
PHP is a dynamic language that includes a lot of concepts, from objects, interfaces and anonymous functions, up to goto labels. The development direction for the language is not very clear, it rather offers the possibility for different approaches.
In the weird PHP history, somewhere in version 4, syntax for Anonymous Functions was added, but only in PHP 5.3 a more “normal” version appeared.
Also in version 5.3 the first closure version was introduced:
1$scalar = 5; 2 3$closure = function () use ($scalar) { 4 return 'Scalar: ' . $scalar . PHP_EOL; 5}; 6 7echo $closure(); // Scalar: 5 8 9$scalar = 7; 10 11echo $closure(); // Scalar: 5
This version mostly worked, but you had to specify what you want to send to the closure.
And there were other inconveniences:
1<?php 2class Foo { 3 private function privateMethod() { 4 return 'Inside private method'; 5 } 6 7 public function bar() { 8 $obj = $this; 9 return function () use ($obj) { 10 return $obj->privateMethod(); 11 }; 12 } 13} 14 15$obj = new Foo(); 16$closure = $obj->bar(); 17echo $closure(); 18 19Fatal error: Call to private method Foo::privateMethod() from context '' in [...][...] on line 10
Is not working because you can not send $this as a parameter to a closure, and if you try the above trick you still can’t access the private methods. Remember, this was happening in PHP 5.3.
The idea to introduce a closure of this kind seems strange to me. But this is not the first time something “strange” is introduced in PHP, as I was saying before about the Anonymous Functions. Sometimes is looking like work in progress.
I think everybody was expecting a more JavaScript like closures. I think that JavaScript had a big influence in making this concept so popular.
In version PHP 5.4 things changed, we finally have a closure as we would expect:
1class Foo { 2 private function privateMethod() { 3 return 'Inside private method'; 4 } 5 6 public function bar() { 7 return function () { 8 return $this->privateMethod(); 9 }; 10 } 11} 12 13$obj = new Foo(); 14$closure = $obj->bar(); 15echo $closure(); // Inside private method
And it works!
You can even do:
1unset($obj); 2echo $closure();
and it will work, because the object in which the closure was defined remains in memory until either the script finishes execution, or a call like this is made:
1unset($closure);
For more details on how closures work in PHP 5.4, check out this post.
-
It’s time to publish another JavaScript game, this time is Minesweeper.
The first version of the game was made about an year and a half ago, but meanwhile I’ve completely rewritten it because of performance issues.
I believe this will be the last game that I didn’t make using canvas for compatibility reasons.
Unlike the other games that were made literally over the week-end (the exception was Puzzle Gd) this game proved to be a little more complicated.
For the design I must thank (again) to Cătălinei Radu.
Enjoy!