-
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.
-
Motivated by Rober Martin’s article, Hoards Of Novices, I’ve decided to write an article on a similar subject.
I do not want to write about the need for employers to hire juniors, but about why these juniors are not up to the expectations and, in the end, what can be done to be better prepared.
The software market is continuously expanding. Software is the way we command a computer what to do. Today, devices around us have processors, software and applications, from phones, watches, TVs and up to washing machines and refrigerators. All these devices need programms and programmers to develop applications for them.
With this premises, we reach the Software crisis. It was concluded that we need to build software faster in order to solve this crisis. This was a popular subject in the ’60s, but in time it has become less important.
To solve this problem, high level languages and frameworks were built. High level languages made development and maintenance of an application much easier. This way, programmers are getting very far from the “metal” of the actual hardware, working with concepts much easier to deal with.
In a world of high level languages (Java, C#, PHP, Python, JavaScript etc.) it is much easier and faster to create an application.
Yet, although developing an application is becoming easier, the quality of the developers is falling.
A consumer society
We need school for a better job.
Because the need for studies is a general need, the school itself is diluting. The educational principles haven’t had significant changes since education became available to everybody. The result of the learning process is the exam, in order to determine the level of knowledge. And even more, a mediocre result allows us to move forward, without prove that the required base is present.
Moving to the next level is done with a partial evaluation, you don’t have to know 100% of the information, just 50-60%. It is not exactly clear if there are important notions in the remaining 40-50%.
This educational problem is more or less a general problem and there are few those who try different approaches.
In general, I don’t consider school a defining system for determining the knowledge, especially today, when we have access to such a large volume of alternatives for it.
When students finish school, they don’t have all the required knowledge to actually work in the industry, which is not abnormal. School must offer a general basis. For instance, during my higher education I can remember at least 8-9 programming languages that we studied. There were actually more, but I didn’t keep a detailed evidence of them. It is clear that you can’t possibly know all these programming languages in order to become productive using them. On the other hand, you have an idea on how to approach them, which may help you to find the one you’ll like to study in thoroughness.
That’s the key, to study in thoroughness! For this we each have our approach, here you can find your own way, either courses, books, practical projects or all of them. By thoroughly studying a subject, the employers will not only accept you, but they will hunt you!
Often, the passion will totally replace the studies from school. I’ve met a lot of people which, even though they haven’t studied informatics in school, they are now professionals in it.
The good part is that a lot of people are studying from pleasure and I advise anyone who is reading these lines to search for pleasure in what they do. This is the best motivation.
Alternative education in a consumer society
Because the traditional learning techniques are no exactly sufficient, let’s talk about a few alternative methods:
- books
- courses
- tutorials
- articles/blogs
Books
Traditionally books are the best source of information (at least until the Internet became available). But there is no guaranty for the quality!
About 8-9 years ago I was trying to buy a JavaScript book. The selection wasn’t very big and so I tried to analyze each one.
In the end I was disappointed with my choice, because instead of teaching me JavaScript, the book was teaching how to make special effects on the page (very popular in that period).
In my particular case, I found the answer much later in a presentation by Douglas Crockford. He said that most JavaScript books are like that and he was recommending a single book, beside the book written by him, JavaScript: The Definitive Guide.
The reason is very simple, people tend to be more drawn by books that promise to teach a language or technology in a limited number of lessons or days. We want everything now, but studying takes time, you must understand the notions, not just a fast overview.
Generally, to determine the quality of a book you should look for reviews. These days it is very easy, I prefer Amazon.com and not only. This way you can determine if it is what you are looking for.
Sometimes a faster approach is useful, especially if you don’t have any previous experience on the subject, but generally this doesn’t offer a general perspective, only a gentile introduction.
Courses
There are a lot of courses, both in-class and on-line. Just like for the books, it is hard to determine the quality of the course.
Courses promise a lot, but a lot of the times they don’t treat the subjects in detail and in the end, even though you have the impression that you have learned a lot, when it comes to practice you realize that any variation from the course material is very difficult.
Just like for books, references are very important! Unfortunately, there aren’t as many reviews for course as there are for books.
Try to see what subjects the course is teaching and the detail of the approach. Sometimes, you can find more easily a reference for the teacher than for the course.
Tutorials
Especially on the Internet, there are a lot of tutorials that promise to teach a certain domain, but they only teach you how to create their example. In the end you can only create small variations of the initial example. Often, the creator of the tutorial has the best intentions, but it is hard to transfer information like this.
For the free ones it is very easy to determine if the approach is the right one for you and for your needs. Try to watch a few episodes and in the end see how much you’ve understood on how that particular component is working. If you can only replicate, maybe you need to search a little more.
The good part is that there are generally a lot of them to choose from. For instance, for a programming language you can first check the official reference to see what you should learn about, then in the tutorial you can see how many of the points from the reference were approached.
For the commercial ones it is a bit harder, because often you just have a small introspective preview, insufficient to form an opinion. For those particular cases you should search for reviews.
Blogs and articles
The good part here is that the time investment is relatively small. It is simpler to get a general idea.
The disadvantage is that some of the articles don’t update with time. You must make sure that the examples work on the version that you are using. From my own experience I can say that keeping an article up to date is hard an takes a lot of time. For instance some of the articles on this blog that still attract visitors are written a few years back and if I don’t use that particular technology anymore, I’m tempted not to keep them up to date.
How to learn better
Search for references and reviews for the materials that will require an investment in time and/or money: books, courses or tutorials.
When you’ve settled on a subject, try to see what materials others recommend. The Internet is full of materials of different levels of difficulty.
When you fell that you’ve mastered a subject, test your knowledge. Build an app, follow the subject on Q/A platforms or even write a tutorial for the others. You tend to understand much better a subject when you have to describe it to others.
Practice! It is very important to practice what you learn or you’ll forget much easier than you think. Contribute to open-source projects, try to do personal projects or try to adapt projects created by somebody else to your needs. Github is a very good tool for finding and publishing projects.
It is a bit harder at the beginning to understand somebody else’s code, but in the industry it is mandatory in order to be able to collaborate with others.
Learn new things all the time. Technology is changing, and so is the perspective over it. For instance, AJAX appeared in the late “90’s, but the perspective over it and how it can be used changed dramatically over the next few years, even though the technology itself didn’t change a lot during that time. The same for JavaScript, even though it appeared in the “90’s, only after 2000 it began to be considered an useful tool, previously it was mainly used for special effects on the page.
For a while, PHP was considered useful only for small projects. Today it is the language of choice for giants of the internet, like Facebook and Yahoo!. Along with the popularity, the best practices on the language itself changed for a better scalability and performance.
Conclusion
The educational system doesn’t offer the performance that employers are looking for. This creates a discrepancy between the expectations of the employers and those of the graduates, and this not restricted to informatics.
Unfortunately, the alternative materials sometimes also promise unrealistic things. Some study technologies and programming languages for months, while others promise results after only days or even hours.
Fortunately, we are living in an era dominated by information, and we can find not only materials, but also opinions about them.
Through better training, the changes of finding a job are rising considerably, resulting in satisfaction on both sides.
-
The newest PHP version is almost ready. At the time I’m writing this blog PHP 5.5 is in RC 1.
As I was saying in my last blog, the feature list is available at: http://www.php.net/manual/en/migration55.new-features.php
The second feature, in terms of popularity, is “finally“: http://www.php.net/manual/en/language.exceptions.php
What’s the deal with “finally“?
It looks a little confusing, is looks like a block that’s getting executed after the “try/catch” finishes. But what is so new about it?
Let’s take a try/catch block:
PHP 5.x < 5.5:
1// open resouce 2$resource = new Resouce(); 3try { 4 // do stuff with the resouce 5 $resouce->doStuff(); 6} catch (Exception $e) { 7 // log exception 8 syslog(LOG_ERR, $e->getMessage()); 9} 10// release resouce 11unset($resouce);
PHP 5.5
1// open resouce 2$resource = new Resouce(); 3try { 4 // do stuff with the resouce 5 $resouce->doStuff(); 6} catch (Exception $e) { 7 // log exception 8 syslog(LOG_ERR, $e->getMessage()); 9} finally { 10 // release resouce 11 unset($resouce); 12}
Up to this point there isn’t any reason for a new block. The exception was catched, it was logged and continues.
But let’s say there is a resource and we need to close it, and after that we need to throw an exception. One way this can be achieved is to release the resource in catch.
But there is still the “successful” case, and we need to release it in that case also.
1// open resouce 2$resource = new Resouce(); 3try { 4 // do stuff with the resouce 5 $resouce->doStuff(); 6} catch (Exception $e) { 7 // release resouce 8 unset($resource); 9 // perpetuate exception 10 throw $e; 11}
Let’s complicate stuff even more, let’s say there are n exception types. It will result in n catch conditions, plus the successful case, and in all of these cases we need to free the resource. Not very efficient…
Another way is to store the exception in a variable and, after the resource is released, to throw the exception, if that is the case.
1// variable to store the exception 2$exception = false; 3 4// open resouce 5$resource = new Resouce(); 6try { 7 // do stuff with the resouce 8 $resouce->doStuff(); 9} catch (Exception $e) { 10 $exception = $e; 11} 12 13// release resouce 14unset($resource); 15 16if($exception) { 17 throw $exception; 18}
This is one way it is done right now. It’s working but it’s not clear that we are only trying to release the resource and continue our lives in peace.
The PHP 5.5 way
In the php.net manual:
In PHP 5.5 and later, a finally block may also be specified after the catch blocks. Code within the finally block will always be executed after the tryand catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.
Each time the block is executed, regardless if it was successful or not, finally will get executed. So, for the next example:
1try { 2 echo 'Do stuff' . PHP_EOL; 3 throw new Exception('testing'); 4} finally { 5 echo 'inside finally' . PHP_EOL; 6}
The output will be:
1Do stuff 2inside finally 3 4Fatal error: Uncaught exception 'Exception' with message 'testing' in...
If we want to also catch the exception:
1try { 2 echo 'Do stuff' . PHP_EOL; 3 throw new Exception('testing'); 4} catch (Exception $e) { 5 echo 'do something with the exception' . PHP_EOL; 6} finally { 7 echo 'inside finally' . PHP_EOL; 8}
The output will be:
1Do stuff 2do something with the exception 3inside finally
And even if we take the particular case when we catch the exception and then throw it:
1try { 2 echo 'Do stuff' . PHP_EOL; 3 throw new Exception('testing'); 4} catch (Exception $e) { 5 echo 'do something with the exception' . PHP_EOL; 6 throw $e; 7} finally { 8 echo 'inside finally' . PHP_EOL; 9}
It seems we prevented the finally block from getting executed? Well, not exactly…
1Do stuff 2do something with the exception 3inside finally 4 5Fatal error: Uncaught exception 'Exception' with message 'testing' in...
In other words, the finally block gets executed each time, regardless of the result.
-
A new PHP version is about to be released. At the time I’m writing this blog PHP 5.5 is in beta 4.
Eager to see the updates, I’ve compiled the new beta version. The feature list is available at: http://www.php.net/manual/en/migration55.new-features.php
The generators are the most important feature..
Generating generators in PHP 5.5
A generator is basically a function that contains a call to “yield”.
Let’s take the example form php.net:
1<?php 2function xrange($start, $limit, $step = 1) { 3 for ($i = $start; $i <= $limit; $i += $step) { 4 yield $i; 5 } 6} 7 8echo 'Single digit odd numbers: '; 9 10/* Note that an array is never created or returned, 11* which saves memory. */ 12foreach (xrange(1, 9, 2) as $number) { 13 echo "$number "; 14} 15?>
Basically, the generator (xrange in this case), instead of returning an array, will return a value at a time, in order to be processed.
But wait… wasn’t this already possible before this version?
Generators before PHP 5.5
Before PHP 5.5 there were already Iterators:
1<?php 2 3class xrange implements Iterator 4{ 5 private $position = 0; 6 private $start; 7 private $limit; 8 private $step; 9 10 public function __construct($start, $limit, $step = 1) 11 { 12 $this->start = $start; 13 $this->limit = $limit; 14 $this->step = $step; 15 $this->position = 0; 16 } 17 18 function rewind() 19 { 20 $this->position = 0; 21 } 22 23 function current() 24 { 25 return $this->start + ($this->position * $this->step); 26 } 27 28 function key() 29 { 30 return $this->position; 31 } 32 33 function next() 34 { 35 ++$this->position; 36 } 37 38 function valid() 39 { 40 return $this->current() <= $this->limit; 41 } 42} 43 44echo 'Single digit odd numbers: '; 45 46/* Note that an array is never created or returned, 47 * which saves memory. */ 48foreach (new xrange(2, 9, 2) as $number) { 49 echo "$number "; 50} 51?>
Beside the fact that the Iterator is an object with multiple properties, basically we can achieve the same result.
But why do we need generators then? Simple! Instead of using ~40 lines of code, we can simply use 5 to achieve the same goal.
Another interesting thing is that:
1get_class(printer());
will return Generator.
Basically, a generator returns an object of type Generator, and this object extends Iterator.
The major difference, as it is described on the php.net website, is that the generator can not be reset, basically it goes one way only.
Sending information to the generators
Yes, generators work both ways, but each generator only works in one particular direction. If the syntax above is for “producing” data, then the syntax below is only for “consuming” data.
The syntax for a “consumer” is simple:
1<?php 2function printer() { 3 $counter = 0; 4 while(true) { 5 $counter++; 6 $value = yield; 7 echo $value . $counter . PHP_EOL; 8 } 9 echo ‘Never executed...' . PHP_EOL; 10} 11 12$printer = printer(); 13$printer->send('Hello!'); 14echo 'Something is happening over here...' . PHP_EOL; 15$printer->send('Hello!'); 16?>
The output will be:
1Hello!1 2Something is happening over here... 3Hello!2
Basically, the value of yield can be used as any other value. What’s interesting is the while. On php.net is the folowing comment:
// Sends the given value to the
// generator as the result of
// the yield expression and
// resumes execution of the
// generator.The loop is needed because the generator will stop after it processes the value and will only continue when a new value is received. If we remove the while, only the first value will be processed, regardless of how many times we’ll call send().
An interesting thing is that what comes after the loop will not be executed, that is in my case:
echo ‘Never executed…’ . PHP_EOL;So, if it looks like a good place to release a resource (e.g. DB or file), in fact it isn’t, because that code will never get executed.
It seems useful for logging. Again, nothing that couldn’t have been done before, but now it allows for an easier approach.
I’ve found though something that doesn’t work:
1<?php 2function printer() { 3 while(true) { 4 echo yield . PHP_EOL; 5 } 6} 7 8$printer = printer(); 9$printer->send('Hello world!'); 10 11foreach($printer as $line) { 12 echo $line . PHP_EOF; 13}
A little chaotic, isn’t it? But I was wondering what would happen:
Fatal error: Uncaught exception ‘Exception’ with message ‘Cannot rewind a generator that was already run’ in…So, once send() is used on an iterator, you can’t use it as an iterator again. Of course, another one can be generated with:
printer();What is more confusing is that Generator is a final class, so it can’t be extended, and if you try to instantiate it directly (although even if it worked it would be useless):
Catchable fatal error: The “Generator” class is reserved for internal use and cannot be manually instantiated in…Conclusion
It is an interesting feature because it simplifies things a lot when you try to create an iterator.
Also the use of send() seems very interesting, not because it is doing something new, but because it is doing it easier.
On the other hand, I don’t like that there is the same syntax for both generator versions and even more that what is after the while is not getting executed. I think the syntax is a little confusing because there isn’t a clear difference between the two. On the other hand, this already exists in Python, so for inspirator the examples from this language can be used.
-
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.