-
Introduction
About a month ago, Facebook released the Hack programming language.
Since then, apocalyptic articles related to this language and to how it will replace PHP have appeared everywhere. The title of this article was inspired by “Will Hack Kill PHP?“.
What is even more strange to me is that it was followed by a wave of negative assessments related to PHP, apparently Hack “fixes” the previously mentioned language. In my opinion, the language has to be “broken” in the first place to be “fixed”.
Off-course PHP has many drawbacks, like any other programming language, but there must be a good reason why it is the most popular language for the Web. After all, Facebook used it for a long time, and now it is not replaced, they are improving it… aren’t they?
One thing is for certain, it is probably one of the least inspired names. When you search for “Facebook hack” you will find anything else but this programming language…
About Hack
Hack is running on HHVM. HHVM is Facebook’s try to optimize the PHP language with Just In Time complication, the latest approach in optimization of the language. Basically, Facebook is trying to reduce their costs by optimizing the language interpreter, and now with a new language all together. After all, if we think about Facebook’s infrastructure, it’s normal for them to do this, even a relatively minor optimization will lead to a consistent cost reduction.
Initially, I thought it was an “improved” version, but it seems like it is another language altogether, basically it’s a PHP with something extra!
A small tutorial of the language is at: http://hacklang.org/tutorial/.
The tutorial doesn’t cover all the features of the language, more details are at: http://docs.hhvm.com/manual/en/hacklangref.php.
Practically, about all the features that differ in Hack from PHP are optional. You can almost write PHP and it will work. Contrarily to expectations, not even specifying the type of the input/output of the variables is not required.
Because after all it’s a different programming language altogether, I’m not going to go into much details on all the new features. That is more the purpose of a book, not an article.
I only want to point out a few features that I found interesting.
Strangely, at least at the begging, at runtime the type of the result, even though it is sent, is not necessarily interpreted.
Let’s take an example:
1<?hh 2 3function a($a): void { 4 return true; 5} 6 7echo a('a');
This example will have the output… 1.
Basically, at runtime only the input type is checked, not the output one.
To run the Typechecker in the current directory, an empty file must be added:
1$ touch .hhconfig
Then run:
1$ hh_client
As you can see, the data types are checked in a separate step beside runtime.
At the manual execution of the Typechecker, it will find all the inconstancies. The purpose is for it to identify the problems before the runtime, for instance when you edit a file, not when the app is actually running.
The Typechecker output is:
1../test.php:4:9,12: Invalid return type 2../test.php:3:17,20: This is void 3../test.php:4:9,12: It is incompatible with a bool
Unfortunately, there is still a lot of work to be done with this feature. If we try to validate only at runtime, using “type hinting” like in PHP, the function becomes:
1function a(int $a): void { 2 return true; 3} 4 5echo a('a');
The output of the Typechecker is not changed, but upon execution the result will be:
1Fatal error: Argument 1 passed to a() must be an instance of int, string given in ../test2.php on line 5
Basically, the Typechecker is doing what the type hinting is not and the the latter is now also receiving scalar type arguments.
Even if the only change was to add scalar arguments checking, I would have still considered it an important improvement.
It is a syntax that is more popular with the functional languages.
An example:
1<?hh 2 3$sqr = $x ==> $x * $x; 4 5echo $sqr(5) . PHP_EOL;
Off course the result will be 25.
I find it a very interesting and clear way to represent small logic.
In the new syntax, a function can also return another function:
1$add = $x ==> $y ==> $x + $y; 2 3$result = $add(1); 4 5echo $result(2) . PHP_EOL;
The result will be 3.
If a variable from inside a lambda expression doesn’t exist in the scope of the function definition, then it will be retrieved from the environment in which the expression was declared:
1// variable in the current scope 2$z = 5; 3 4$addZ = $x ==> $x + $z; 5// change the variable in from current scope 6$z = 6; 7 8// perform the add 9echo $addZ(1) . PHP_EOL;
The result will be… 6!
The equivalent in PHP is:
1$addZ = function ($x) use ($z) { 2 return $x + $z; 3}
The value of $z will be retrieved for the environment where the function was defined, not as a reference to the variable.
Off course that’s not the case when the variable from the outside of the function is an object, in this case it will be passed by reference:
1<?hh 2 3class a { 4 public function __construct(public string $x) {} 5 public function __toString() { 6 return $this->x; 7 } 8} 9 10// variable in the current scope 11$z = new a('Claudiu'); 12 13$addZ = $x ==> $x . ' ' . $z . '!'; 14 15// change the variable that will be used for concatenation 16$z->x = 'World'; 17 18// run the concatenation 19echo $addZ('Hello') . PHP_EOL;
The output will be:
1Hello World!
Again, a syntax more popular with the functional programming languages. The purpose is to validate a more specific type of structure than an array.
The reason is very good, validate simple data structures. The structures that are getting checked should contain the elements defined in the shape.
1<?hh 2 3// defining a structure 4newtype Circle = shape('radius' => int); 5 6// a function that will is using the type of the structure above 7function areaCircle(Circle $param) { 8 return M_PI * $param['radius'] * $param['radius']; 9} 10 11// a series of shapes that are using the structure 12$circle = shape('radius' => 10); 13$cilinder = shape('radius' => 10, 'height' => 15); 14 15// a structure that should not work pass as Circle 16$sqr = shape('side' => 10); 17 18echo areaCircle($circle) . PHP_EOL; 19echo areaCircle($cilinder) . PHP_EOL; 20echo areaCircle($sqr) . PHP_EOL;
The output is:
1314.15926535898 2314.15926535898 3 4Notice: Undefined index: radius in /home/brand/test.hh on line 6 5 6Notice: Undefined index: radius in /home/brand/test.hh on line 6 70
A little disappointing, I was hoping that the parameter that doesn’t match the structure will trigger an error, but it passes.
Not even the Typechecker finds anything wrong.
The intention is very good, now we just have to wait for the working version.
Conclusion
Probably Hack will influence PHP, which is normal in the end, it happens all the time with programming languages.
Will it replace PHP? I don’t think so, probably there will be a lot of adopters for cost reduction or a better structuring of the code.
It is not very kely for this language to be successful in the following years other than for projects of medium and large sizes. For small projects usually shared hosting is used, and this generally doesn’t have the latest PHP version, it is even less likely for it to have the latest HHVM. This is probably one of the least interesting arguments, but in the end most of the websites on the web are of small and very small size, they make up the “mass”.
An easier approach to optimization is to only use HHVM. In theory, you don’t have to change anything and the results should be visible immediately! Practically HHVM is not 100% compatible with Zend Engine, but this problem is getting less of an issue with each version. One of the priorities for HHVM is to interpret the code the same way Zend Engine does, but to be much more efficient!
-
The year has just started and a new PHP version is preparing for release. At the time when I’m writing this blog, it is in alpha 2. It can be downloaded from here: snaps.php.net.
There is a series of interesting features, but today I’ll approach only 3 of them: constant scalar expressions, variadic functions and arguments unpacking.
Constant scalar expressions
This first feature is also the only one that didn’t have an equivalent before this version. And, when I say equivalent, I mean only for classes.
Until now, constants defined using the keyword “const” didn’t allow any type of expression, only a scalar value could be used, ex:
1const INT_CONST = 1; 2 3const STRING_CONST = "string"; 4 5const HEREDOC_CONST = <<<'EOT' 6nowdoc 7EOT;
Of course, there is also the more interesting version, which allows setting constants with dynamic values:
1define('DYN_CONST', $variable);
The bad part is that this type of constants are not available for a class, because for a class only const can be used.
This means that now we can use:
1const ONE = 1; 2const TWO = ONE * 2; 3const STR = "string of one and two :" . ONE . TWO;
And if it’s not enough, there is always:
1define('FLAG', true); 2 3const EXP = FLAG ? ONE : TWO;
Basically, we can set dynamically a value for a class constant! For instance, you can set like this in a constant the environment type for the user, dev or prod.
Variadic functions
This is the feature that I like the most, even though there is an equivalent for it in the older versions.
Currently, if you want to create a function with a variable number of parameters, you can:
1function variableParameters () { 2 $params = func_get_args(); 3 foreach ($params as $parameter) { 4 echo $parameter . PHP_EOL; 5 } 6} 7 8variableParameters(1); 9variableParameters(1, 2); 10variableParameters(1, 2, 3);
There are several problems, more or less obvious, with an approach like this:
- From the function signature it is not clear that it accepts more parameters, on the contrary, it seems that it doesn’t take any;
- func_get_args can be called anywhere in the function. If it’s on the first line, the purpose will be obvious, if it’s on line 20, it’s hard to spot and may generate confusion.
An alternative is to add a number of parameters, but this is not a good indication of the varying behavior.
And here is the new approach:
1function variableParameters (...$params) { 2 foreach ($params as $parameter) { 3 echo $parameter . PHP_EOL; 4 } 5}
In this new version, it’s clear what is happening with the function parameters. You don’t have to figure out if and how many parameters the function can take, it is clear that the number varies!
Usually, when I’m looking for a function, I look for the definition in the IDE before checking out the documentation, especially when there is little or no documentation.
Arguments unpacking
The problem that is approached here is: there is a function with multiple parameters and they are sent in a dynamic fashion.
As I was saying previously, there are alternative ways to solve this problem. Let’s use the function from the previous example:
1function variableParameters () { 2 $params = func_get_args(); 3 foreach ($params as $parameter) { 4 echo $parameter . PHP_EOL; 5 } 6}
And let’s say there is a variable number of parameters, moreover they are stored in an array. We don’t have a lot of options to pass them:
1$params = ['param1', 'param2', 'param3']; 2 3call_user_func_array("variableParameters", $params);
The result will be:
1param1 2param2 3param3
In PHP 5.6 we can use those 3 points, similarly to the way they were used in the example from “Variadic functions”, but the other way around. Instead of the parameters that are received by the functions, they are the parameters being sent to it:
1variadicParameters(...$params);
Maybe for this type of example it is not very clear, but if there is a fixed number of parameters for the function and a fixed number of parameters that are sent:
1function twoParams($a, $b) { 2 echo $a . $b . PHP_EOL; 3} 4$params = ["Hello", "PHP 5.6!"]; 5 6twoParams(...$params);
Even though it’s not something that couldn’t be done in the previous versions, now it’s more elegant.
And to conclude, the two examples:
1function variableParameters (...$params) { 2 foreach ($params as $parameter) { 3 echo $parameter . PHP_EOL; 4 } 5} 6 7variableParamerers(...["cool", "parameter", "unpacking"]);
I think with these small changes, PHP is making the transition from “the PHP way” to “the best way”, taking from other languages.
-
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!
-
In movies where hackers appear, source code appears flowing in rivers on the screen. Looks important, seems like there is a computer genius that is preparing to revolutionaries something.
Ever wandered what that epic code from the movie is? John Graham-Cumming has done a collection of movies and the source code used in them: http://moviecode.tumblr.com/.
-
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.