#52WeeksOfCode Week 23 – IRC Chat

Week: 23

Language: IRC Chat

IDE(s): Messages + Jabber + BitBee + Chatzilla

History (official):

(From the homepage of #irchelp)

“/I-R-C/ n. [Internet Relay Chat] – IRC provides a way of communicating in real time with people from all over the world. It consists of various separate networks (or “nets”) of IRC servers, machines that allow users to connect to IRC. IRC is very similar to text messaging, but designed around communicating with large groups of users instead of one on one.”

History (real):

Kids, way back in 1988 (ask your parents), the Internet was still mostly called the Arpanet and was not available to average people. Even if you did have access, you had to use your phone to connect to it.

Not your cell phone but a regular old-timey phone. You know, that thing plugged into the wall at your grandparent’s house that they use to  talk with you at Christmas?

Anyway, the Internet For The Rest Of Us(™) consisted of Bulletin Board Systems (BBSs). These were PCs sitting in someone’s basement connected to a phone line. Still dial-up,sure, but you could share files, play games, chat with other users and have lively discussions.

Though BBSs had a chat program, Jarkko Orkarinen, a student at University of Oulu in Finland, decided that he wanted Internet users to be able to connect with BBS users. So while he was upgrading the chat program on his university BBS, he developed IRC (Internet Relay Chat).

IRC is still around, despite having lost a lot of its user base. Its arcane command syntax makes it intimidating for non-technical users, but its flexibility and open standards make it a useful platform for automated messaging. For example, two normally incompatible software programs that have no communication mechanisms in common can easily be set up to exchange data via IRC.

Discussion:

IRC is actually a communications protocol. In other words, a set of language rules. Any programs that speak IRC can talk to each other, regardless of operating system or platform. IRC sends and receives messages in plain text which makes it pretty easy to write code for both servers and clients. That being said, it’s not exactly the Queen’s English:

/join #52weeks

is the command to join a chat room (channel) named 52weeks. On the other hand, pretty much any program that can send or receive text can speak to an IRC server.

I’d like to bring IRC kicking and screaming into the 21st century for my own amusement. In other words, I want to use the default chat application on my MacBook (Messages) to talk to someone on IRC.

The challenge is that Messages doesn’t know how to talk to IRC and vice-versa. However, there is an open messaging protocol called XMPP (eXtensible Messaging and Presence Protocol). Originally named Jabber, the idea was to create a sort of lingua franca for instant messaging.

The first step is to install a Jabber server. The easiest way to do this is with Openfire. It’s easy to setup, open source and cross-platform. I got the server running, setup an account for myself, pointed Messages to the server and I was up and chatting.

Connecting to Jabber from Messages

Connecting to Jabber from Messages

Okay, there was nobody to talk to but the point is, I was at least able to talk to myself.

Now to set up a gateway to connect my Jabber server to my IRC server. I’ve already set up an IRC server using ngircd (installed from MacPorts). I can verify the server is working by connecting to it with Chatzilla, a Mozilla Firefox addon that lets me easily connect to an IRC server using the URL irc://<server_name> in the location bar.

It’s important to use the same username on the IRC end as on Jabber. A gateway’s good but it can’t read your mind.

Now for the protocol gateway to connect Jabber with IRC. I chose BitBee, a Linux/UNIX  IRC server that knows how to connect to other instant messaging services. I installed BiBee using MacPorts, stopped the ngircd server (I didn’t need it anymore) and started BitBee.

Chatzilla connection to BitBee

Chatzilla connection to BitBee

The key to managing BitBee is the &bitlbee channel. This is where you add the accounts for your other chat services. I set up a Jabber account called tsinclair_irc with the password ‘password’ and added the account to BitBee:

account add jabber tsinclair_irc@macpro15.local password

Now to test the connection. First I sent a message from Jabber to IRC:

Connecting to IRC from Messages through Jabber

Connecting to IRC from Messages through Jabber

Now to see if the message came through on Chatzilla:

Message to Jabber from IRC

Message to Jabber from IRC

I sent “Hello yourself!” back:

Message from Jabber to IRC

Message from Jabber to IRC

Let’s look at the setup from 100,000 feet:

Overview of my messaging setup

Overview of my messaging setup

All along the way, I went for the easy option where available though parts of it were harder than they needed to be.

 

#52WeeksOfCode Week 33 – Groovy

Week: 33

Language: Groovy

IDE(s): Eclipse with Groovy plugins/Groovy Shell

 

History (official):

(From the Groovy Home Page)

Groovy…

  • is an agile and dynamic language for the Java Virtual Machine
  • builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk
  • makes modern programming features available to Java developers with almost-zero learning curve
  • provides the ability to statically type check and statically compile your code for robustness and performance
  • supports Domain-Specific Languages and other compact syntax so your code becomes easy to read and maintain
  • makes writing shell and build scripts easy with its powerful processing primitives, OO abilities and an Ant DSL
  • increases developer productivity by reducing scaffolding code when developing web, GUI, database or console applications
  • simplifies testing by supporting unit testing and mocking out-of-the-box
  • seamlessly integrates with all existing Java classes and libraries
  • compiles straight to Java bytecode so you can use it anywhere you can use Java

History (real):

Since this is the third or fourth language I’ve encountered that produces code for the Java Virtual Machine (JVM), I decided to search for “java is dead”:

Searching for "java is dead"

Searching for “java is dead”

Apparently the Java Death Watch has been around since 1996. This raises the bigger question “When is a programming language actually dead?”.

According to the Linguistics Society of America, a human language is considered dead when there are no more native speakers.

Computer languages are trickier. Is a programming language dead if no computers are left to run it or is it when there are no programmers who still use it? If we decide to adapt the definition of ‘dead’ from human language (no more native speakers), we need to ask “What is the computer equivalent of a ‘native speaker’?” This puts us back to square one so that’s no help. We should probably just see how good of a case we can make for either choice.

  • Computers as ‘Native Speakers’ – Computers actually ‘speak’ machine language, 1’s and 0’s. This is very hardware and operating system specific, like different dialects of English (same characters different syntaxes). Every programming language command has to eventually end up translated (directly or indirectly) into machine language. For modern coding languages, the underlying hardware doesn’t make that much of a difference. This argument is a non-starter.
  • Programmers as ‘Native Speakers’ – This makes more sense to me. The code is still around and still runs but nobody is writing new programs with the language, then the  language is dead. Or, to use the phrase of art, in ‘maintenance mode’. (see COBOL)

Groovy is another scripting language that produces code that can run on the Java Virtual Machine (JVM). Others include JRuby, Scala, Vala, Fantom and Jython. In effect, they are all dialects of Java, since you can mix Java code with any or all of them and they run just fine.

So is Java dead? Let’s just say that the rumors have been highly exaggerated.

Discussion:

Groovy is cross-platform and there are a number of ways to install it.

  • Download the binary package and unzip it wherever you want
  • Install the Groovy plugin in either Eclipse or NetBeans
  • If you’re on a UNIX-based machine (like Mac OS X or Linux), you can install the GVM (Groovy enVironment Manager).

I already had Eclipse after installing the Scala IDE (i.e. Eclipse with the Scala plugin) so I went with the  Groovy plugins for Eclipse. It was pretty straightforward.

Once I plugged in the location of the Groovy software, I got a nice selection of add-ons. I just selected what I needed:

Minimum Groovy plugin install

Minimum Groovy plugin install

A quick download, install and restart of Eclipse and I was off to the races. When I came back, there were additional choices in my New menu:

Starting a new Groovy Project

Starting a new Groovy Project

I selected Groovy Project, took the defaults and (like the Scala project) opened up with no source code, just project scaffolding. I had to add a Groovy class to the project to get some source I could work with.

There are three ways to run your Groovy code:

  • Run as Java Application – This compiles Groovy into Java bytecode and runs it on the JVM
  • Run as Groovy Script – Don’t compile, just run the script with the Groovy interpreter.
  • Run as Groovy Console – This is the most interesting option to me. When you choose this, your code opens up into a separate window:
Running in the Groovy Console

Running in the Groovy Console

This gives you an interactive console where you can do some quick experimentation with your code. This is a good choice for rapid development, letting you test out chunks of code before rolling them back into your main project.

Since I’m also comfortable with the command line, I installed the GVM for good measure. It’s pretty easy and gives me access to a command-line Groovy interpreter. Like the Groovy Console, this lets me test out chunks of code for rapid development. Once it’s installed you just call it with the command groovysh:

Starting up Groovy Shell

Starting up Groovy Shell

A sample Hello World in groovysh:

Running Hello World in Groovy Shell

Running Hello World in Groovy Shell

This is not the preferred option for Groovy newbies. I would recommend that you stick with Eclipse or Netbeans.

One of the things that interested me about Groovy was the claim that you can drop Java code into a Groovy script and it will just work as Java and Groovy share virtually the same syntax.

I tested this out with Eclipse. I created a quick Java version of “Hello World!”, copied and pasted the code into my Groovy project (commenting out the original code) and it worked!

Java code with Groovy - it works!

Java code with Groovy – it works!

This gives Groovy an additional advantage, as Java programmers will have a much less steep learning curve when the transition to Groovy.

 

#52WeeksOfCode Week 32 – Assembly Language

Week: 32

Language: Assembly

IDE(s): SciTe + NASM

History (official):

(There is no one version of Assembly language since it is aimed at specific hardware. However, I did find this in the Forward for The Art of Assembly Language by Randall Hyde which I thought was amusing):

Egads. What kind of book begins this way? What kind of author would begin the book with a forward like this one? Well, the truth is, I considered putting this stuff into the first chapter since most people never bother reading the forward. A discussion of what’s right and what’s wrong with assembly language is very important and sticking it into a chapter might encourage someone to read it. However, I quickly found that university students can skip Chapter One as easily as they can skip a forward, so this stuff wound up in a forward after all.

So why would anyone learn this stuff, anyway? Well, there are several reasons which come to mind:

 

  • Your major requires a course in assembly language; i.e., you’re here against your will.
  • A programmer where you work quit. Most of the source code left behind was written in assembly language and you were elected to maintain it.
  • Your boss has the audacity to insist that you write your code in assembly against your strongest wishes.
  • Your programs run just a little too slow, or are a little too large and you think assembly language might help you get your project under control.
  • You want to understand how computers actually work.
  • You’re interested in learning how to write efficient code.
  • You want to try something new.

 

 

Well, whatever the reason you’re here, welcome aboard. Let’s take a look at the subject you’re about to study.

History (real):

I feel the need to lend some perspective before I dig into Assembly language, otherwise known as Assembler.

This is a picture of the first personal computer ever sold, the MITS Altair (from OldComputers.Net):

MITS Altair image, courtesy of OldComputers.net

The First Personal Computer

 

The Altair was introduced in January of 1975. It had 256 bytes of RAM (up to a maximum of 64K), a 2.0 MHz Intel 8080 CPU and was available for $395 as a kit. You got a box of parts. You had to make your own circuit boards. If you wanted it pre-assembled, that was an extra $255.

I want to draw your attention to the front panel of this computer. Yes, I mean all of the blinky lights and flippy switches. If you wanted to program this personal computer, you had to flip the switches on the front panel, entering your commands one word at a time in machine language (a series of 1’s and 0’s).

Now because there was no floppy drive, no hard drive, no secondary storage of any kind, if someone happened to trip over the power cord while you were flipping switches, you had to start over from the very beginning.

I mention this to tell you that no matter how arcane and hard to write, maintain, debug, read and understand Assembler is, things could be (and have been) much, much worse.

Discussion:

While Assembler was a step up from machine language, it wasn’t what you would call a giant leap. You still have to shuffles 1’s and 0’s around and have a deep understanding of the underlying hardware of your computer, but at least it took slightly less time to write code.

But if we now have all of these high-level languages, why bother writing code in Assembler?

  • Speed – Assembler programs are extremely efficient and very fast.
  • Size – The efficiency of Assembler also means that programs take up very little space.
  • Power – Since you’re working very close to the hardware, you can do things with Assembler that you can’t do with higher level languages

It’s not as if you have to choose between one or the other. If you have a section of code that needs to run quickly and efficiently you can write it in Assembler and hook it into your higher-level code.

For this exercise I decided to use NASM (The Netwide Assembler), a free, cross-platform assembler for Intel-compatible processors. There doesn’t seem to be a good IDE for Assembler (rumors exist of an Assembler plugin for Eclipse) so I’m going to use a text editor. Though NASM is available for Mac OS X, documentation on how to use it is limited or out-of-date. Linux, on the other hand, is well-documented so I’ll be using Debian 7 for my development platform and SciTe as my text editor. It’s free, cross-platform and does syntax highlighting for a number of common programming languages.

I looked for a “Hello World!” program in Assembler and thanks to a very nice tutorial from Ray Toal at Loyola Marymount University, this is what I found:

Hello World in Assembler

Hello World in Assembler (Using the SciTe text editor)

Compiling and running just involved a bit of typing.

Compiling and running code

Compiling and running our code

Before we look through the source, let’s see what’s happening at the command line.

nasm -felf64 hello.asm

The source code file is called hello.asm. This command tells NASM what format (-f) the output should take. In this case it’s 64-bit ELF (Executable Linkable Format, the standard binary format for Linux executables, object code and software libraries). NASM takes the source code (hello.asm) and compiles it into the object code file hello.o. Object code is machine code, a set of binary instructions.

However, as far as the computer is concerned it’s just a pile of 1’s and 0’s.

ld hello.o && ./a.out

There are actually two commands here.

ld hello.o

The first runs the linker (ld) to link the object code with the ABI (Application Binary Interface) for the target platform. It’s like putting a ‘Start’ button on our code so our processor knows how to run it. The default output is an executable called a.out. The line

./a.out

runs the program to print “Hello World!”. The ‘&&’ between the two commands simply means ‘if the first command succeeds run the second command, otherwise just stop’.

Now let’s go through the source code line-by-line:

# ----------------------------------------------------------------------------------------
# Writes "Hello, World" to the console using only system calls. Runs on 64-bit Linux only.
# To assemble and run:
#
#     gcc -c hello.s && ld hello.o && ./a.out
#
# or
#
#     gcc -nostdlib hello.s && ./a.out
# ----------------------------------------------------------------------------------------

 

Anything that starts with a pound sign (hashtag for you youngsters) is a comment and is ignored by nasm. This is pretty standard Linux syntax and you may see the semicolon (;) used for a similar purpose on other platforms.

       .global _start

The global keyword marks symbols that need to show up in the output (hello.o). As you might suspect, NASM is showing the linker where the executable starts.

       .text

This is just a name for a section of code. Remember, the output is just a string of 1’s and 0’s which could mean anything, depending on where you start reading and how many bits you read at a time. This keyword .text tells us that that the following section is runnable code, not data.

_start:

As stated above, here’s where our actual code starts, in case it wasn’t obvious.

       mov     $1, %rax
       mov     $1, %rdi
       mov     $message, %rsi
       mov     $13, %rdx

A machine language instruction consists of two parts, the opcode (what the code should do) and the operand (the data on which the opcode should act). In these four lines, .mov is the opcode for loading data into a register (a small fast chunk of memory used for temporary storage). These four instructions copy data into the registers rax, rdi, rsi and rdx.

The first (rax) holds the location of the system call we’re going to use, which is write ($1).

The second (rdi) is the memory location where we’re going to write our message which is standard output ($1).

The third (rsi) is the string we’re going to write to output. ($message is just a label for the string data, which we’ll find elsewhere in our code. Hang on.)

The fourth (rdx) is how much of our message to print, 13 bytes (or characters).

We’re loading a sequence of commands. Write 13 bytes of our message to standard output. It’s like setting up a series of dominoes, just waiting for that lone finger to start the string of activity.

And here comes the finger:

            syscall

Since our system already knows how to print strings, why reinvent the wheel? This opcode tells our processor to read the four sections of memory we’ve set up and act accordingly. We still have to tell the processor we’re done so let’s set the dominoes up again.

       mov     $60, %rax
       xor     %rdi, %rdi

The first loads the exit command ($60) into our register rax. The second is the exit code for our program to spit out, in this case 0. Ready for the finger again?

       syscall

Finally we come to our data section.

message:

       .ascii  "Hello, world\n"

This is labelled with message: so we can refer to it elsewhere in our code, as we saw above. In this case, it contains the string that we want the system to print to standard output. It’s labelled as plain old alphanumeric text, because we have to specify how we want the processor to interpret those 1’s and 0’s.

On the plus side, Assembler is a very powerful way to write fast code that takes up very little memory space. On the minus side, you have to keep track of where your data is at all times and what takes a single line of code in a high-level language takes thirteen in Assembler.

Not that there’s anything wrong with that.

Hyde, Randall. The art of assembly language. No Starch Press, 2003.

 

#52WeeksOfCode Week 29 – Clojure

Week: 29

Language: Clojure

IDE(s): NightCode

History (official):

(From the official Clojure home page)

Clojure is a dynamic programming language that targets the Java Virtual Machine (and the CLR, and JavaScript). It is designed to be a general-purpose language, combining the approachability and interactive development of a scripting language with an efficient and robust infrastructure for multithreaded programming. Clojure is a compiled language – it compiles directly to JVM bytecode, yet remains completely dynamic. Every feature supported by Clojure is supported at runtime. Clojure provides easy access to the Java frameworks, with optional type hints and type inference, to ensure that calls to Java can avoid reflection.

Clojure is a dialect of Lisp, and shares with Lisp the code-as-data philosophy and a powerful macro system. Clojure is predominantly a functional programming language, and features a rich set of immutable, persistent data structures. When mutable state is needed, Clojure offers a software transactional memory system and reactive Agent system that ensure clean, correct, multithreaded designs.

I hope you find Clojure’s combination of facilities elegant, powerful, practical and fun to use.”

 

History (real):

That was the equivalent of a marketing release for Clojure. In other words, it’s targeted at the ‘suits’. If you want the sales page for the technical crowd, see the Rationale page.

I have no personal animus against Clojure. Today was the first time I had heard of it. But I have to say that my first thought was “What? You mean I can at last combine the terse, unreadable code of Lisp with the performance hit of running Java? Sign me up!”

Of course, the true story is more complex.

One of the strengths of the Java platform is the Java Virtual Machine (JVM). A Java program compiles to bytecode which runs on the JVM. The JVM gives Jave its portability between operating systems. Microsoft’s .NET language followed suit with the CLR (Common Language Runtime).

Another advantage of the JVM, however, is that Java bytecode is an open, documented standard. That means that you can use any programming language you want to write Java applications, as long as you can compile your language to produce bytecode. Examples include Jython and JRuby that let programmers write Java programs in Python and Ruby, respectively.

Clojure lets programmers write in Lisp and produce code that can easily integrate with Java and code that uses Microsoft’s .NET framework. It can also connect to JavaScript libraries like Node.js for Web applications.

This is a cool idea. Scripting languages do make for faster prototyping and development and bytecode compilation does improve performance a bit (but not as much as going all the way down to machine code).

But why Lisp for scripting? Let’s ask the creator of Clojure, Rich Hickey. From the Clojure Rationale page:

Why did I write yet another programming language? Basically because I wanted:

 

  • A Lisp
  • for Functional Programming
  • symbiotic with an established Platform
  • designed for Concurrency

 

I think the third feature is the important one. We already have multiple dialects of Lisp. Erlang is a functional programming language that supports concurrency. But neither of these can integrate so easily with existing code as Clojure.

I think that if I had a complaint, it would be that the scripting language was based on Lisp. But that’s my own personal discomfort and unfamiliarity with functional programming and not meant to diminish Hickey’s accomplishment in any way.

Discussion:

So how do I get started coding in Clojure? After a bit of research, I found that writing the code was easy enough but a real Clojure project involves keeping quite a few metaphorical plates spinning. Managing all of the files, code dependencies and project details can get hairy very quickly, particularly if you work from the command, which is the bare-bones Clojure install default.

There is an existing tool, make, which can handle code projects but it’s finicky to configure. Java has similar project management issues which are handled by a tool called ant. Fortunately some contributors to Clojure created an automation tool named leiningen. It works so well that it’s become the default tool for working with Clojure projects.

I didn’t feel like working from the command line (again) so I searched for a nice IDE for my first Clojure project. There are Clojure plug-ins for popular Java IDEs like Eclipse, NetBeans and Intellij but I wanted a program that was built specifically for Clojure.

Enter NightCode. Not only was it written for Clojure projects, but it was written in Clojure. I felt this showed admirable brand loyalty so I grabbed a copy. The interface is pretty bare-bones:

NightCode on first startup

NightCode on first startup

I only have three options: Create a new project, import an existing project or run code interactively in the little interpreter window on the lower left. This is a pretty neat feature because you can jump out of your current project, quickly test out some scrap of code to make sure it works the way you think it does and then paste it back into your main source file without leaving the IDE. Very nice:

NightCode interactive shell

NightCode interactive shell

I created a new project and after giving my project a name was presented with a list of project templates:

NightCode template selection

NightCode template selection

I like templates. They let me get on with my life.

I picked Console and selected Create Project.  In a few moments my first project was ready to code:

A simple console application project

A simple console application project

I have a few more options now. One thing I noticed were the options Run, Run with REPL, Build and Test. Since Clojure is a scripting language, it’s possible to run code without actually creating an application. Run with REPL runs your code interactively which is useful for debugging. Test checks your code for logic and syntax errors. Build, of course, creates the standalone software application. It’s still a very sparse interface, but it looks like you could do some non-trivial projects in this IDE. Not bad for free software.

On to my trivial project. The console project template is a standard “Hello World” so I use it to take both Clojure and NightCode for a spin.

Here’s the code, in case you’re curious:

Hello World in Clojure

“Hello World!” in Clojure

I’d like to test my code before running it so Test automatically inserts test code into my program, compiles and runs it:

Automatic code testing

Automatic code testing

Selecting Run gives me this:

Running my code

Running my code

Run with REPL loads the code and drops me into an interactive shell:

Running interactively with REPL

Running interactively with REPL

Now I’m ready to create my standalone application with Build:

Building a standalone application

Building a standalone application

Clojure is a unique, versatile language and NightCode gives me enough tools to handle non-trivial projects with confidence.

#Book Review – Code Reading

The reading of code is likely to be one of the most common activities of a computing professional, yet it is seldom taught as a subject or formally used as a method for learning how to design and program.

 

Aspiring writers are always told to read as much as they can if they want to become better writers. As Dave Thomas points out in his foreword to Diomidis Spinellis’ Code Reading, aspiring programmers almost never get this advice. By code, of course, I mean the program source code, the fundamental recipe for any piece of software.

Imagine that you’re taking a writing course. You get assignment after assignment – persuasive essays, memos, poetry, research papers or prose. Now imagine that you have to do every one of these assignments from scratch, without any examples. You have to work everything out yourself.

This is the traditional method of teaching programming. I know because I used to teach programming classes.

Code Reading is both refreshing and an eye-opener. Not only does Spinellis present a solid case for the habit of reading program source code, he also fills his book with code examples, complete with commentary. Though the examples are mainly from Java and C, the lessons learned can be applied to any programming language.

Just to be clear, the code presented is not from the toy examples found in programming textbooks. This is material from real, working software projects. The book covers major programming topics and even includes analysis of a complete, working program. Spinellis gives tips and techniques for the novice code reader to aid them in developing their skills.

From my own experience, reading code can be very educational, even entertaining. Every programmer tries to put their own personal stamp on their work and part of the fun is seeing the human mind behind the algorithms.

For example, I was teaching game software development and wanted to get my students some practice in reading code. We downloaded the source code for BZFlag, a tank game based on the video game BattleZone combined with Capture the Flag. It’s a fun, cross-platform game that you can play solo or over the Internet with teams.

There was one particular feature in which I was interested. During play, you can set your tank to AutoPilot mode and let it play for you. This makes a nice change from having to pause your game whenever you have to get up and take care of business.

We grovelled through the source code files for a bit and I finally found the sections having to do with AutoPilot. As I read them, I spotted some code that looked very intriguing but was never actually called by any other part of the program. It looked like someone was trying to build a heuristic system for the AutoPilot mode. In short, it was meant to have the program build a solution starting with the goal and working its way backwards. It was very clever and had a lot of potential. I could add see why it hadn’t been  implemented due to the inherent complexity of the method.

The fact that the code was just left there, unfinished, was fascinating. When I saw that code, I put myself in the mind of that programmer. I’ve also had coding ideas that got stuck in blind alleys. But here was someone like me, trying to solve a problem in an interesting way and failing that, leaving a note for the explorers to come after in hopes that they would ultimately succeed where he did not.

This book shouldn’t just be on any programmer’s reference shelf, it should also be the basis of at least one undergraduate programming class.


Spinellis, Diomidis. Code reading: the open source perspective. Addison-Wesley Professional, 2003.

#52WeeksOfCode Week 22 – PHP

Week: 22

Language: PHP

IDE(s): TextWrangler plus MAMP

History (Official):

(From the homepage for the PHP Group)

“PHP is a popular general-purpose scripting language that is especially suited to web development.

Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world.”

 

History (Real):

PHP is a very popular programming language and runs on over 200 million Web sites, including some very large ones like Facebook. Not bad considering PHP was not originally conceived as a programming language.

According to creator Rasmus Lerdorf in a 2012 interview with the IEEE house magazine Computer, PHP was originally just a collection of utilities he hacked together to make his web page development easier. He found he was writing the same code over and over again for his clients so like any good coder he took it upon himself to automate the process.

All well and good.

But other programmers saw what he was doing and asked for copies of Lerdorf’s toolkit. Hackers being who they are, when they found bugs they fixed them and passed the changes back. Eventually he handed off responsibility for pieces of his code to others and PHP grew in scope. Each programmer added functionality to scratch their own particular itch and contributed their code back to the community. Lerdorf mostly stayed out of any code architecture decisions, preferring to leave that to the community.

Those of you who are familiar with the open source development process may see the fundamental flaw here.

For the rest of you, let me explain. When you set out to create a programming language (or any non-trivial software project), you create a specification. This is a document that sets out the conventions that everyone has to follow in order to participate. For example, you make a list of keywords, words that have special meaning in the language. This lets others know that these words can’t be used for anything else.

With a specification document, you can have many developers working on the project and have some assurance that they won’t be stepping on each others toes.

A specification document can and does get updated but it’s usually in a way that adds features or project scope without significantly changing the basic rules.

Next, even an open source project staffed by volunteers needs someone who is the final word on changes. This could be an individual (like Linus Torvalds with Linux) or a group (like the team that manages Debian).

Without these, the software project has no real structure. Features get added and taken away without much of an explanation and some functionality may be either missing or duplicated by multiple redundant methods.

The fact that PHP is so widely used and seemingly robust is more of a testament to the heroic efforts of the community of PHP developers who are applying spit and baling wire to make this code work.

But there are always consequences.

Just for fun, I searched for ‘php sucks’ and got almost 10,000 hits. After glancing through the links, here are some of the most common complaints:

  • The code libraries are a disorganized mess
  • Unnecessary duplication of functionality
  • No coherent design
  • Messy and complex
  • Incorrect or incomplete documentation
  • Data input needlessly complex or error-prone
  • Poor code readability

These are some of the milder complaints. There are more, but you need to be a programmer to fully appreciate the horror.

I don’t blame Lerdorf. By his own admission, PHP was never meant to be a programming language. It was just a bunch of neat, useful hacks that a talented, enthusiastic community of programmers adopted as their own. In a sense, the story of PHP is a pure expression of the Hacker Ethic.

NOTE: This is not a PHP hit piece. As I’ve said, I’m not a professional programmer, just an interested bystander. I have no dog in this fight. I just have an incurable compulsion to lend perspective.

Discussion:

First off, we need to install PHP. This is pretty easy. You can either use one of the pre-built installers or just build it from scratch.  Mac OS X comes with free programming tools as an optional install so I already have PHP on my system.

In theory you can use PHP like any other scripting language, but since it’s designed for Web development you really need to set up a Web server that understands how to run PHP code. Fortunately some very smart people set up a software stack called LAMP (Linux-Apache-MySQL-PHP) as a free, turnkey solution for Web development. LAMP started out on Linux but variants are also available for other platforms, such as MAMP for Mac OS X or XAMMP for Windows.  What they all have in common is easy installation and setup.  I’ll be coding on my MacBook so I’ll be using MAMP.

Now I just need a text editor so TextWrangler it is. I could use something fancier like Aptana, NetBeans or Coda but I don’t plan on coding up anything terribly complex.

Since I’m not looking to do anything fancy, I created a simple form. The user is asked to input a number between 1 and 10 and press Submit.

Enter a number

Pick a number…

Then the number gets passed to another page, where a simple loop prints “Hello World!” based on the number entered by the user.

Hello World five times

This fellow is very friendly!

I felt this was an appropriate spin on the standard “Hello World!” program as PHP was originally designed to manage HTML forms.

#52WeeksOfCode Week 21 – Facebook API

Week: 21

Language: Facebook API

IDE(s): TextWrangler with MAMP

History (Official):

(From Facebook’s Facebook page)

“Founded in 2004, Facebook’s mission is to give people the power to share and make the world more open and connected. People use Facebook to stay connected with friends and family, to discover what’s going on in the world, and to share and express what matters to them.”

History (Real):

Letting us connect with friends and family and all of the other sharing and caring doesn’t pay the bills.

Facebook makes money by selling the attention of its users.  If that’s a problem for you, don’t get an account.

That’s pretty much all I have to say about that.

Discussion:

Officially, Facebook provides SDKs (Software Development Kits) for IOS, Android, Javascript and PHP. There are also third-party providers that offer support for other languages such as Objective-C, Java, Ruby, Python and Flash. Facebook does not offer support for these third-party kits.

I like to keep things simple, so I’ll be using the Facebook Javascript SDK. There is no software to download or install. You simply need to add a short section of code to your Web page. When the page is loaded into a browser, the Facebook SDK will automatically load itself.

First I need to get Facebook to recognize me as a developer. I select Register as a Developer from the Apps menu on http://developers.facebook.com (after logging in with my Facebook account). I’m asked to re-enter my Facebook password.

FB Password Verification

Password Verification

I agree to Facebook’s policies.

FB Policy acceptance

Facebook Policy Acceptance Dialogue

I’m asked to confirm my registration by entering a code that will be sent to my phone by either a text message or a phone call. Facebook seems to be unable to text to my phone for some reason, so I picked Send via Phone Call. In a few moments, my phone rang and a friendly automated voice told me my code.

Account Verification Code

Account Verification Code

Finally I was successfully enrolled as a Facebook developer. I haven’t written a lick of code yet but I still feel like I’ve accomplished something.

Now I need to get an ID and secret token for my app. These identify my software to Facebook so they can manage what I can and can’t do and also keeps other developers from pretending to be me. (Twitter and other social networking services have similar methods.)

After a couple of false starts (my app title contained a trade name, which is verboten), I was sent to a page which provided the Javascript code (whichincluded my app ID and secret token) to insert in my Web page to load and initialize the Facebook API.

I created a page called fb_test.html and saved it in my MAMP local site folder. I inserted a bit of code to add a Like button on the page, loaded it up and it worked!

Testing the Like Button

Like Button Test Successful!

So far, so good. Now I’d like to send a message to Facebook from my page. I replaced the Like button code with the code for a Send button. A quick page reload later and voila:

Send Button Load

Loading the Send Button

Now to compose a message to myself:

Composing a Send

Just saying hi….

Meanwhile, over on my Facebook account:

Message received

Hey! I got a message!

Overall, it was a very pleasant experience. Granted, I wasn’t doing anything complicated, but I appreciated the hand-holding. Sample code was easy to find and worked first time. The documentation was readily available and easy to browse.

I almost hate to say it, but this was probably the most pleasant developer experience I’ve had to date. Whatever your opinion of Facebook, and everyone’s got an opinion, I can’t fault them here.