What should be my lingua franca of programming?

In a fast paced business environment with fast changing requirements, the tools for expressing and constructing a program become extremely vital for the productivity of the programmer. Given this assumption, the primary of these tools, the choice of programming language becomes extremely essential for productivity. Having worked in C and C++ and having seen a host of different languages I have formed a vague idea of where I am headed next. My attempt is to find out which language should be my lingua-franca of programming.

I am a clear advocate of the horses for courses philosophy, however, it is also important to work with a language that best shapes my thinking. I have here a list of languages I am acquainted with and hopefully a choice emerges and hope that one of these quickly becomes an arrow in my quiver (that I am able to build at least something substantial and useful with it). I had scribbled down the following languages and their pros and cons and hope to master one of them by the end of the year (a 10000 hours later…). Each of these languages have already been used in production and proved their value well already for other companies.

Here is my humble attempt to deconstruct the pros and cons of each language and use one of them before jumping headlong into one.


Erlang

The grand daddy of all the “Programming in the Large” languages. In spite of its quirky syntax (read non-C typish), it is a revelation to work in a language where there is no mutability. In fact, once I worked in Erlang, it has forever changed my way of thinking about data problems. My typical PHP or Python code is now littered with a lot of small functions returning tuples where earlier I was prone to over-engineer with a lot of classes.

Killer app

  • ejabberd (/mongooseIM) – XMPP
  • CouchDB
  • Riak

Pros

  • Immutable programming model
  • Modules + Function overloading
  • Good set of BIFs
  • Interop with C (performance optimization)
  • Robust and scalable with OTP
  • REPL

Cons

  • Weird syntax (non Cish) – strict naming conventions (might be a win actually) – Elixir might be a big win here actually!
  • Low real world usage (might be an offshoot from above)
  • Slow
  • Not so great plugins for common usecases (webapps) – mysql

Scala

Scalable language or Scala we call is one of those languages which target the JVM directly. And being a hybrid language, it has found good reception among codistas.

Killer app

  • Play
  • Twitter – Finagle
  • Typesafe platform

Pros

  • Java interop – so support for Netty is directly available – Batteries included
  • LISP + Object oriented + Functional = multi-paradigm language
  • REPL
  • Touted as the future of Java
  • Compiles to Java bytecode so almost as fast as similar Java code

Cons

  • New language
  • Multi-paradigm – philosophy of 1 language – many ideals
  • Mix of immutable (val) and mutable (var) – tries to be too many things to many people

Go

Go is a new language from Google which seems to have a C type syntax as well as the fundamentals of programming in the large systems.

Killer app

  • Docker
  • Google Infrastructure

Pros

  • Looks like C – small learning curve
  • Compiled
  • Backed by Google
  • Battle tested
  • Performance close to C
  • Goroutines

Cons

  • Not used by a lot of companies – hard to find developers in the market
  • Still very recent and not fully battle tested

Clojure

Coming with a LISP syntax and a immutability as a core tenet it is a refreshing take of LISP in a JVM. Created by Rich Hickey, its driven very strongly by its creator, the language is quite opinionated.

Killer app

  • Datomic
  • Clojure Script

Pros

  • Java interop – Batteries included
  • LISP syntax – almost
  • REPL
  • Touted as the future of Java
  • Rich Hickey’s philosophy
  • Channels

Cons

  • New language
  • Lisp Style

Python

My lingua franca now. It is very neatly done language and the fact that it is objects (dicts) all the way through is extremely refreshing.

Killer app

  • Django

Pros

  • REPL
  • Good / Fixed syntax
  • Simple modules
  • Batteries included approach – powerful glue, scripting and even a general purpose language
  • pip

Cons

  • Lacking multicore support
  • STM
  • Green threads

Lua

While not being in the same league as these full-fledged languages, Lua is one of those languages that can quickly turn an extremely well performing C / C++ code and turn it into a powerfully scriptable system without losing any of the performance

Killer app

  • Open Resty
  • Game programming systems

Pros

  • C / C++ support
  • Performance / Speed

Cons

  • Not a full-fledged language. Any errors bubbles up from the base language directly into Lua

Conclusions

All said, there are a few features I like in a programming language I like working with …

  • REPL
  • Modularization of code without having to resort to using classes. This is where PHP loses out for me.
  • Installable modules. Batteries included approach.
  • Variables naming with hyphen instead of underscores or camelCase. Feels more natural
  • Function naming with question mark. Makes reading and building boolean returning functions ending with a ? a natural read.
  • Garbage collection. I have seen C, C++ and Erlang’s immutability and any language that does not have me worrying about the trivial pursuit of hanging pointers is a big win!
  • Homoiconic systems. It becomes very easy when we start thinking about data and code not as two separate lines of thought (storage, DRY, versioning) but as two varying types of storage semantics only. Where processing (code) and data systems can both crash and need to be restored on demand, it becomes extremely useful when the code itself can be used to express infrastructure, data, configuration and other systems.
  • Clear and convention driven programming style. Telling me that it will work the way it looks (WYSIWYG) is simply a huge win. Quite simply, Erlang excels here for me. So does Go and Python.

My only crib. I wish Elixir was in the Python syntax instead of Ruby (of course taking nothing away from Ruby – its an extremely natural language – just a bit too Englishy and flexible for my taste).

Linux commands output in PHP

My friend Rahul was giving me a demo of their Web UI and a small but nifty feature caught my eye. They had a feature of being able to configure their systems using the Web UI (which is pretty cool in itself!) and the console output from the configuration command in turn would be displayed in a html iFrame. My company has a similar internal tool which does the same but then showing the output in a step-by-step manner would really be a huge help.

Anyways, so cooked up a quick php function for our system. Hope someone finds this snippet useful.

Erlang Ring Code

Erlang Ring Benchmark Problem:
In the Programming Erlang book by Joe Armstrong, we find this problem at the end of the Concurrent Programming chapter.

Write a ring benchmark. Create N processes in a ring. Send a message round the ring M times so that a total of N * M messages get sent. Time how long this takes for different values of N and M. Write a similar program in some other programming language you are familiar with. Compare the results. Write a blog, and publish the results on the Internet!

My contribution to the already growing list of Erlang Ring Benchmark problem. However this is just the code for the Erlang, a N ring setup and M messages moving around the ring in parallel.

Moved to WP 2.5.1

Finally moved the site to WordPress 2.5.1. My own personal blog has been on wordpress.com and that UI was quite inspiring. Now I stand inspired. And definitely the ease with which WP upgrades is quite awesome. However it would have been even greater if I could just upgrade by clicking on a button without even having to download, upload files!

Multiuser Chat using Flex and Ruby

For the last few days I had been googling for some good help for coding networked flash applications for a pet project of mine. Mostly using Flex & Ruby. There have been quite a few I saw – made with flash and using Java; but nothing to my personal liking. And hence I set to build a prototype of my own.

Being a coder and a poor (financially & aesthetically & skillfully :D) visual designer, I am totally in love with Flex for the visual quality it brings to the flash applications i can build.

Ruby for the beauty it brings to the code; but then the code is only as good as the coder. And for cooking up a quick prototype, no language has been so good of course except for Perl (for me ofcourse).

Multiplayer – thats a tricky question. Flash cannot support P2P (peer-to-peer) applications as yet. So the best choice available is to use a client-server architecture – the good ole’ sockets.

Hence using the code from a lot of different places and porting them from other languages, I managed to quickly cook up a Flex multiuser chat application with a ruby backend. Without further ado, into the code.

The server right now runs on the 9999 port of the localhost and the client connects to the same host and port. If you plan to test it on a hosting server, make sure you change the host and the port.

Note: My wordpress code plugin is fucking up the mxml code. For this part you may just download the zip file and use the client.mxml.

The Flex client:

< ?xml version="1.0"?>

	
		< ![CDATA[
			import flash.display.Sprite;
		
			import flash.net.XMLSocket;
			import flash.events.Event;
			import flash.events.DataEvent;
			import flash.events.IOErrorEvent;
			import mx.events.CloseEvent;
			import mx.controls.Alert;
	
			public var socket:XMLSocket = new XMLSocket();
			private var host:String     = "localhost";
			private var port:int        = 9999;
	
			public function init():void	{
				socket.connect(host, port);
	
				socket.addEventListener(DataEvent.DATA, onData);
				socket.addEventListener(Event.CONNECT, onConnect);
				socket.addEventListener(Event.CLOSE, onClose);
				socket.addEventListener(IOErrorEvent.IO_ERROR, onEvent);
			}
			
			private function onConnect(event:Event):void	{
				board.htmlText += "Client: Connected to server" + "
"; } private function ReconnectHandler(event:CloseEvent):void { if (event.detail == Alert.YES) init(); } private function onClose(event:Event):void { board.htmlText += "Disconnected from server" + "
"; Alert.show("Reconnect to the chat?", "Reconnect?", (Alert.YES | Alert.NO), this, ReconnectHandler); } private function onEvent(event:Event):void { board.htmlText += "Error" + "
"; trace(event); } private function onData(event:DataEvent):void { board.htmlText += event.text; } private function sendMesg():void { socket.send(username.text+ ': ' + mesg.text + "n"); mesg.text = ""; } ]]>
.marginstyle { paddingTop:12; paddingBottom:12; paddingLeft: 12; paddingRight: 12; } .spacestyle { paddingTop:2; paddingBottom:2; paddingLeft: 2; paddingRight: 2; }

To compile it to a swf
Assuming you already have the free Flex SDK just use
$> mxmlc client.mxml
which will create a client.swf file for you.

Multiuser Ruby chat server:

#!/usr/bin/ruby
require 'socket'

MSGS = {"init"    => "Server started. Waiting for connections...",
        "welcome" => "Welcome! type EXIT to quit",
        "byebye"  => "Disconnected from server"}

EOF     = "00"
HOST		= "localhost"
PORT		= 9999

server	= TCPServer.new(HOST, PORT)
puts MSGS["init"] 

# array to store all the active connections
sessions = []
while (session = server.accept)
  # push the current session(socket) in the array
  sessions < < session
  # initialize a new thead for each connection
  Thread.new(session) do |local_session|
		local_session.puts "#{MSGS["welcome"]}" + EOF

    # each time a client sends some data send it to all the connections
    while(true)
      data = local_session.gets
			
			if !data.nil?
				delim_pos = data.index(":")
				name      = data[0..delim_pos-1]
				data      = data[delim_pos+1..-1]

				if data[0] == EOF
					data = data[1..-1] 
				elsif data.chomp == "EXIT"
					sessions.delete(local_session)
					local_session.puts "#{MSGS["byebye"]}" + EOF
					local_session.close
					
					data = "#{name} disconnected from the server" + EOF
				end
			end

      sessions.each do |s| 
        begin
          s.puts "#{name}: #{data.chomp}" + EOF
        rescue Errno::ECONNRESET
          # an exception is raised, that means the connection to the client is broken
          sessions.delete(s)
        end
      end
    end
  end
end

To Run
User ruby chat_server.rb

Source Code: Download here. It contains a simple single user server – java & ruby versions [simpleServer.java & server.rb], a multiuser server [chat_server.rb] and the client [client.mxml].

Anyone, any doubts can leave a comment.