Wednesday, October 19, 2011

Which Programming Language? CoffeeScript, Java, PHP


Today we are going deeper on the importance of feedback when choosing a programming language.

Did you try to spike a little with a new programming language? A very useful way to do it is through the measure of feedback you have from the language and its environment or ecosystem.
So if you tried to download, install, compile... (stopwatch at hand) good! If you didn’t, I’m going to free you from the effort through this and other next posts, so keep in touch.

Which Language?

Let’s consider two “old” languages: Java and PHP and a new one: CoffeeScript

Which Platform?

I’m working on a Mac, and so let’s suppose we want to deploy on it.
It’s important to define your platform because you can try something on a platform and deploy on another one, but of course if you change it on the way, you have an unknown.

Which Context?

I’m writing during the weekend and, unlike other working days, I usually take a nap after lunch, it’s something I’ve been carrying since I was young, it’s a break in the daytime and it lasts about 30 minutes or so, a sort of reversed pomodoro or, better, a pomodoro focused on sleeping ;-)
After that, I’m "energized" and ready for the afternoon. So what?
  1. Let’s consider a preliminary of N languages (only three today) some mainstream, some cutting edge. The goal is to hack a timer that wakes me up from my nap after 30 minutes.
  2. Note: some languages implement sound generation more smoothly; other are not really sound-friendly, so for this first attempt, a timer that prints “wake up” is enough.
  3. Finally for this specific experiment I’d add another requirement: let’s jump to light speed and go somewhere in the universe where 30 minutes are equal to 3 seconds (my nap is incredibly reduced ;-)
psst: If you are lazy like me, you can go directly to the Conclusion, otherwise continue to read.

First I create a directory named contest in which we save all our spikes.



The first language to consider is Java


I create a subdirectory for Java and look for Java on Google like any newbie.

Following my breadcrumbs with some comments:
Actually we have spent 6 minutes, but no info worth on. 

So I search for something like “first java program” on the favorite search engine and..... at 8.36 minutes I land here:
The output is OK (after 10 minutes

But.... our exercise doesn't end here, how can we implement a timer?

I search again: “java timer”
I do a bit of c&p, remove all comments, compile and run. It works (17.20).
Now I reduce frills, and change time to 3 seconds

After 18.05 minutes we have our timer:

import java.util.Timer;
import java.util.TimerTask;

public class ReminderBeep {
  Timer timer;

  public ReminderBeep(int seconds) {
    timer = new Timer();
    timer.schedule(new RemindTask(), seconds * 1000);
  }

  class RemindTask extends TimerTask {
    public void run() {
      System.out.println("Time's up!");
      System.exit(0);
    }
  }

  public static void main(String args[]) {
    new ReminderBeep(3);
  }
}

Anyway the Java syntax is not concise nor essential, but 18 minutes is a pretty fast time even if I was almost confident to read the example for windows.




Now let’s pick PHP


I go to:
I try to write the hello.php file and then I point the browser directly on it.
  • vi hello.php 
  • a bit of c&p 
  • open browser on file://......../hello.php it doesn’t work, of course. 
I surf the web again:
I locate and open the Apache configuration file, it should be here: /private/etc/apache2/httpd.conf and I change it accordingly.
Than I go to: /Library/WebServer/Documents and I write a simple phpinfo

<?php phpinfo(); ?> 

Now I restart apache with: sudo apachectl graceful and then I point the browser here: http://localhost/info.php, it works.
Now I move hello.php here: /Library/WebServer/Documents , it works

After 27.00 minutes we have:

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <?php echo '<p>Hello World</p>'; ?> 
 </body>
</html> 


Now I make a search for a timer on Google: "php timer example"

Finally after 43 minutes that’s the simplified timer: 

<?php
sleep(3); 
echo "wake up<br />";
?>

As you have seen, php drives you to use a web server and to execute the code inside it, even if we have not a real need to build up such infrastructure.
I’d like to underline this concept: of course php scripts run in a web server.... at the end. But now, our focus is to learn the language, all other “mandatory” steps distract us from our goal and put it away. I don’t think about it as a" una tantum" stuff, I think as a clue you have to evaluate the language ecosystem and the intentions of the creator of the language.
Anyway the php example is really minimal compared with java.




And finally CoffeeScript


The usual breadcrumbs:

Now I create the directory coffeescript under contest then
  • sudo npm install -g coffee-script 
  • I test the installation, type: coffee - Cool it runs.
  • I type: number = 42 - OK, it returns 42 it seems working,
  • And I exit the REPL, how? It could be: exit, no, quit, no, bye, no, open sesame no way.
I'm defeated. I google: "exit coffeescript repl"
I exited, but it’s not yet clear to me how to print something, let’s look deeper at the overview and try:
  • alert “hello” - ReferenceError: alert is not defined 
  • coffee -e "console.log num for num in [10..1]" - Gotcha! 
  • console.log "hello" - That's fine.  
 After 29 minutes

Finally let's look for a timer:
http://stackoverflow.com/questions/4917567/coffeescript-timer-and-this-pointer-on-callback - found it.

Now I rearrange the script in the coffee repl to have something like:

setTimeout((-> console.log "wake up"), 3000) - It works!

After 38 minutes



Actually CoffeeScript is really playable and it has a minimal syntax, but I expected a more clear documentation: the repl delayed me a bit


Conclusion

Let's sum up some results:


The chart shows the time spent doing installation plus some initial check and the time spent hacking a timer.

PHP and CoffeeScript result in the same amount of time for the installation, but hacking a simple timer in CoffeeScript is quicker and it's comparable with Java, but I can't tell you more, the trial is not ending here and I still need a couple of posts to show other insights.

Next week time we'll analyze three other languages, keep in touch and... mind the feedback!






Chicken timer by abbey*christine
Installation by zigazou76


Tuesday, September 27, 2011

Two Reasons Your Favorite Programming Language Becomes Cumbersome

Regarding "Is Your Programming Language A Burden?", a couple of days ago, a reader asked me:
“How can I find a language more cumbersome the more I use it?”

Nice question and the answer is quite simple:

  • The first reason can be that the language was born cumbersome, but we didn’t have the fine taste to recognize its useless complexity. 
Let’s take an example: think about String class in Java or C# you know it’s final/sealed, you cannot extend it to open its behavior. Moreover you cannot modify it because it’s integrated with the language (grrrrr). I can bet when programmers realize those obstacles they become aware that language holds their creativity.

  • The second reason is about a language born simple, but release after release, version after version new constructs are stuffed in and finally it becomes bloated.
Look at  Java history and pick your top worst updates.

In conclusion, the more you play with a language the more you discover if it solves your programming needs or if it’s only a parking brake.



P.S.
There is a third reason of course: a language starts cumbersome and in the meantime grows with useless syntax additions, that's the worst case dear readers ;-)


photo by http://www.flickr.com/photos/reiver/

Friday, September 23, 2011

Is Your Programming Language A Burden?

Hi folks,
 How are you? I'm fine, coaching a bit, programming a bit, observing, planning.

As you are reading this blog, I guess your workdays look like mine: wondering who was able to write that messy code (it's you, last month, you know) but you are not an ordinary developer you study, you delve... and day after day, while you are improving, you have a feeling your programming language is slowing you down.

It's something I often see: at some point you feel the language doesn't follow your thoughts, suddenly the syntax becomes cumbersome, types are a cage, primitives reduce your ability to create concepts.

In "How To Choose A Programming Language" I talked about feedback and level of magic and I'd like to hear your voice: did you measure the feedback of your favorite programming languages? You can do it now ;-)
Tell me about it on Twitter @Varvello or Facebook or Google+ or wherever


Thursday, September 15, 2011

How To Choose A Programming Language

Welcome back. It has been a long time since my last post, but I was on vacation than my fish was sick and I needed to take it to the vet and my neighbor's daughter got a round hair brush stuck in her hair and I needed to help her get it out and in addition I fell off a ladder fixing the roof on my house and I landed on my elbow and etc. etc.

Anyway, in the last post, Wordpress vs. Blogger II, I stressed the importance of feedback and how it’s valuable for a programmer to gather feedback from her daily tools. More the feedback is fast, more we learn and more we can tune our product. If we have a result back in a month we learn after a month, if we have it in a week after a week in a second after a second.

I also give you this tidbit: our brain is very fast, it reacts in a jiffy: some days ago I was looking at my wife struggling with a web page where there was a button that said: “to reload press here” so I told her: “look at the button, don’t press it”. I didn’t end the phrase yet and my wife started moving her mouse over the button, she began reacting immediately.
Brain’s feedback is really fast, to be more effective I should have said something like: “don’t press the button now it's useless".

But I’m digressing.

As a programmer needing to be productive, which kind of language should I use? Which criteria are valuable? Where should I start?

Let’s suppose on the web there is some hype about a new programming language and you are almost interested in it, so you bring a reference book, after which you should focus on three things:

  • Feedback: how long it takes from the first time you see a line of code on the reference to the time you have that line running on your pc. That includes: downloading, installing, configuring, compiling… (stopwatch at hand).
  • Feedback: how it’s easy to play with the language. Close the reference and spike a bit. Can you immediately have some results? Are error messages communicative?
  • And of course, Feedback: look for something more complex e.g. saving data of a web page on db. Does the language solve it in a couple of lines of code? It means it’s very powerful, but be careful, that’s what I call: Level of Magic. It’s not really a drawback per se but you should be aware that the language does a lot of stuff in a very few lines of code, if you have to change something, you’ll have to understand its behavior and actually that behavior is hidden -> high level of magic.

Now, I give you an example of the second kind of feedback. The example is not new, but it’s something that has been fascinating me for a long time.

Comments in Smalltalk are enclosed in double quotes:
“this is a comment”

Of course a comment can be like this one:
“example {1.2.3.3}as:Set”

I can select  {1.2.3.3}as:Set  and evaluate it, I can execute a comment and see the result. That comment is living, I can play with it... I can learn: fascinating.

Monday, July 25, 2011

Wordpress.com vs. Blogger II

Here we are at the second episode of Wordpress.com vs. Blogger.
As you know my first motivation is simplicity. The second one is... look at the following videos:





Did you see? Blogger performs some actions faster than Wordpress.com.

The creation of a new post is slower on Wordpress.com (~6 secs) than Blogger (~3 secs) .
Blogger's autosave is within one minute, Wordpress.com autosave is within two minutes and moreover, if you want to manually save your draft, look at the video! The action is not really immediate.
Finally also on preview Blogger is faster than Wordpress.com.

Conclusion: you can easily imagine, when you write a post, you start dropping a few lines, than see how they look like, than rewrite and see again and so on. That's why feedback while editing a text is important.

Now I've a question for you, when you write a program are you editing a text? Indeed, it is something more than editing a text, we need feedback and more. So next post we'll see how a few languages, like Smalltalk, can provide you a fast feedback.

See you.

Monday, July 4, 2011

Wordpress.com vs. Blogger

If you are reading this post, probably you are aware last week I changed blogging platform: from wordpress.com to blogger.
I specified wordpress.com because there is also a wordpress.org but that's the carry-over-your-shoulders  platform.

The very first days I set up my blog, I found on the net a lot of useful plugins for wordpress, wonderful - I said - I tried to install some plugins or to search for the right option in .com, but unfortunately they was for the .org version (side note: dear reader, you have to know I'm a simple mind, I get lost immediately when I find something it's not crystal clear).
Finally I discovered the difference: .com is all-inclusive but restricted, .org is free as a bird but you've also to mount an ikea wardrobe.
I discarded the .org solution sure the .com version was downhill all the way.

Now, let see the "easy" way:

Wordpress.com Dashboard


In your personal wordpress.com dashboard there are: five items in the top bar and fourteen items in the admin bar on the left, i.e. nineteen first level items, but  if you expand every item there are many others links or buttons eager to be clicked.   G o s h.

Now let's go to the blogger dashboard

Blogger Dashboard


Six first level (tabbed) items, plus a "view blog" link

Why do you want to start a blog? Probably because you want to write something worth of and I say writing, not configuring or searching for the right option or whatever else. All other activities are needed but should be done with less hassle. Writing should be immediate!
I've to admit the settings tab in blogger is quite crowded and can be simplified, but almost all the default options are ok.

Good, that's enough but I'll tell you more in the next post.
See you.

Update: The second part of this post is here: Wordpress.com vs. Blogger II


Thursday, June 23, 2011

...Change No.1

Ah-ha, here we are! Welcome again.
As you can see, you can find all my "old" posts here. I hope you like this new home.
 Stay tuned.

Wednesday, June 22, 2011

10 Smalltalk One Liners to Impress Your Friends

Some days ago, Antonio posted a list of 10 Ruby one-liners. The 1-liners saga started with

  Scala,

    then

      CoffeeScript,

       Haskell,

         Clojure,

           Python,

             Groovy

Very good, everyone wants to impress his friends, perhaps She could impress your friends more. Anyway, the grandaddy of programming languages, Smalltalk, is alive even if its voice is weak.

So, let's start

Multiply each item in a list by 2
(1 to: 10) collect:  [:each | each * 2]


Sum a list of numbers
(1 to: 1000) inject: 0 into: [:sum :each | sum + each]


Verify if tokens exist in a string
words := {'smalltalk'. 'akka'. 'play framework'. 'sbt'. 'typesafe'}.
tweet := 'This is an example tweet talking about smalltalk and sbt'.
words anySatisfy: [:each | tweet includesSubString: each]

but Collection>>detect: is more speaking and you can have the first occurrence back

words := {'smalltalk'. 'akka'. 'play framework'. 'sbt'. 'typesafe'}.
tweet := 'This is an example tweet talking about smalltalk and sbt'.
words detect: [:each |tweet includesSubString: each]


Reading a file
(FileStream fileNamed:'test.txt') contents.
Wonderful.


Happy Birthday
Transcript show:'Happy Birthday to You\Happy Birthday to You\Happy Birthday dear Davide\Happy Birthday to You' withCRs
Less geeky than the Scala ex., but more simple and communicative ;-)


Filter a list of numbers
#(49 58 76 82 88 90) groupedBy: [:n| n > 60] 


Fetch and parse an XML web service
XMLDOMParser parseDocumentFrom:(HTTPSocket httpGet:'search.twitter.com/search.atom?&q=smalltalk')



Find minimum (or maximum) in a list
#(49 58 76 123 82 88 90 -3) max
#(49 58 76 123 82 88 90 -3) min


Parallel Processing
Hmm, there isn't an easy way, you should use a specific VM such as:
Polycephaly or RoarVM, but I have no direct experience on them


Sieve of Eratosthenes
sieve := Array new: aNumber withAll: true. 
sieve at: 1 put: false. 
2 to: aNumber do: [:i | (sieve at: i) ifTrue: [2*i to: aNumber by: i do: [:k | sieve at: k put: false] ] 

That's a snippet I posted some years ago. It's not a one liner, but like Antonio I think it's readable.


First Bonus! - Size of running objects
Array allInstances size 
You can see, it's easy to find all instances of an object and calculate their total size.


Second Bonus! - Fast code cleanup
SystemNavigation new allUnsentMessages
Calling allUnsentMessages you can find all methods none call. Sigh, they are very very sad, nobody is interested in them, you should clean up your code :-)

See you next time!

Tuesday, June 21, 2011

You are an innovator

Are you doing the very same things, every day in your life? And you feel you are stuck like a fly in a spider's web.

Probably you are not alone!

But if you are so obsessed to find a way to get rid off them, so, they'll call you innovator.

Reuse, Reduce, Recycle...again

Ok fine, it was an intense week folks, the team struggled with a lot of legacy code (arghh) . Anyway, do you remember Up With People, Reuse Reduce Recycle about two posts ago? Good, I'm going to tell you a story:
Let's suppose you want to go to New York City (are you living there? Ok, stop reading this post, go out, jog in central park, eat something at Bubba Gump etc. etc. etc.).
Let's move on, you are not living in NYC, not in Brooklyn, Queens... but far from Manhattan and you are looking for a flight from your hometown to The Big Apple, so you browse some flight search engines.
One more hint: you are not someone who likes to socialize, to chit-chat, to talk about the weather, you are not human you are... a programmer! Are you living in NYC and you are human? Stop reading this post, go out, jog in...
As you are a programmer, you want to know some of the internalities of flights and how data is transferred from server to client. Finally during your adventure as a novice Sherlock you find at 85%... hmm at 91%... hmm at 97.49% an: XML.

When I find an XML, I always think to myself: I could merrily develop with my favorite language (Smalltalk you guess), why should I face with XML, the Bernie Madoff of languages, something that robs semantic from riches (Smalltalk) to put it in the trash?

In this context you can have something like:

<route>
      <flights>
            <flight>
                  <flightNumber>123456</flightNumber>
                  <departure>Milan MXP</departure>
                  <departureTime>10:30 AM 20110101</departureTime>
                  <arrival>New York City JFK</arrival>
                  <arrivalTime>12:30 PM 20110101</arrivalTime>
            </flight>
          .
          .
      </flights>
</route>

That annoying structure is multiplied for thousands of flights and I don't want to mention: fares, meals, taxes, types of airplanes and so on. You can easily imagine how this xml can be cumbersome.
What can be useful is a mechanism to take a root object (Route) on the server, packing it with all its attributes, transferring it on a client and restoring it there. Many languages support this mechanism: it's called serialization, in Smalltalk you can use a special object: SmartRefStream to easily serialize any object tree.
Ok... ok... I can hear your objections: "XML is a serialization format", "XML provides interoperability" I know, but SmartRefStream is there, smiling at you, there is no need to invent another fashionable format if I can use an effective one, we don't need interoperability, we need operability! We want to use and reuse it, we want to reduce the complexity, not to introduce a new format. But you know I'm not human, I'm a programmer, but not a programmer, I'm a smalltalker.
See you folks.

Is Obama a software guy?

Last week, with the end of Osama Bin Laden, President Obama ended a tangent started ten years ago. It was an expensive digression, but now, in some way, it's a full stop. I don't know what is the involvement of Mr.President in software, even if his campaign had some contributions by agile people, but we, as software developers, should learn from that lesson: to commit implementing a feature and delivering it. It's not a software specific issue, it concerns every professional that wants to be reliable: to promise and to keep the promise.

Reuse, Reduce, Recycle

A long time ago I hosted some guys of Up With People for about a week, they arranged a lovely show in my hometown dancing, singing... we had a lot of fun.
I mind a song named "Reuse, Reduce, Recycle" actually I can't remember the lyrics, but at that time, the song, favoured by a nice riff, stuck in my mind for a while.

I'm not here to advertise on how to be green, but to reflect on software building.
How many times did you think that to implement an HTML page was only a matters of minutes? Unfortunately, you spent one very single day fighting with CSSes and browsers and when you thought you were done, a colleague showed you that increasing fonts the layout was compromised. Arrrgggg!
Or... you are a JS warrior and you want to use that very nice feature of JQuery to impress the customer that is behind you looking at the screen of your pc. Unfortunately the version of JQuery you have in production is a couple of years old and there is no trace of that nice feature you love (of course, a multitude of other services are using that old, but running version of JQuery... and you want to change it? Brrrrr).

That's a standard scenario, but let the UWP guys give us a hand.
How? Next time folks :-)

My Truth, Your Truth

From time to time I see some buzz on "my truth", "your truth", "their truth". Language evolves, but in some cases, meanings are deliberately distorted to undermine the power of words. It does not exist my truth or your truth only my opinion or your opinion.


That's my opinion.

You are wonderful!

Because you are the reader of my blog ;-)