Why programmers are always in their own world

programming staring at code

Have you seen a document full of code recently? Your answer is either “Yeah, too many” or “Nope, can’t remember the last time I saw a coder friend coding” – it’s probably not something in between.

This duality probably has something to do with the total non-existence of programming in most school curriculums. As a result, programmers are often misunderstood as loners, unhygienic and unkempt people who drink too much coffee and sleep way too little. Either that or “they are all hipsters.”

Aside from the vibe that programmers unwittingly exude, I’d say that the nature of programming also encourages—necessitates, even—a particular behaviour among those who practice it. Programmers can sometimes look like zombies to other people.

Why? Here’s my guess: programming requires concentration. Clean, pristine and unhindered concentration. Otherwise it’s just impossible to write code!

You can think of code as pseudo-English. For a piece of software to be actually useful, it has to be dynamic. In other words, it cannot ever be hard-coded – it must be able to accommodate different inputs and produce a bunch of computed outputs according to them. Writing in sort-of English is difficult enough. Writing an architecture that allows values to be stored, mutated (computed) and transferred around to do what the programme is intended to do is much harder.

That’s why programmers always appear bent over staring into the black screen with colourful words – if they don’t, they’ll get lost. And finding their way back will require even more energy and time hunched over their desks.

(image: Tirza van Dijk)

The better way to console log

As JavaScript code is being executed by the browser, the value stored in variables change dynamically. When a user clicks on a button on a page, for example, a block of code (usually a function) gets executed. In a typical programme, executing a function will make use of the computer’s ability to, well, compute, to do some computation and store the value in a variable.

With every click and even movement of the cursor (if the programmer coded that way), the value of variables are altered. Variables constantly change in value, so a problem arises when we want to know what a particular variable’s value is at any point in time when the programme is running. When a programme doesn’t work as intended, programmers exclaim in dismay that there is a bug. And then proceed to debug.

Let me just put it out there: debugging is a science, not art. It can easily *feels like an art to a beginner programmer like me though.

The science of debugging involves methodically testing and isolating the problem. Here’s a common list of things that have bugged me in my short programming career:

  • ; – missing semicolon
  • } – missing closing braces
  • misspelling – (now a thing of the past with JS-linter-standard tool
  • placing a line of code one line too high in an if/else statement
  • placing an array declaration before its constituent variables are declared
  • calling clearInterval(id) directly after setInterval(function(), delay)

Each time one of these show up I spend somewhere between 10 minutes to an hour trying to isolate the problem. Over time, the amount of time spent debugging will decrease over time as I start to recognise patterns. It will also shrink as I become more conversant with debugging tools.

The simplest debugging tool–and the one I use most often–is the trusty console.log(). The console is a developer-facing tool that prints out information as a programme executes. Putting in a line of console.log(variableName) doesn’t take much time, but can potentially save a programmer hours of time. It prints to the console a ‘log’ of something, like a variable value.

Console logs will print to the developer console whatever you ask it to print in real time as the programme executes (anyone can launch dev tools in their browser – if you’re using Chrome it’s Cmd + Alt + J). It’s a beautiful tool, graceful but formidable.

Though before today, I was using it wrong. There are two ways to write a console log:

The first is the way I’ve been using console logs – with a + operator. Behind the scenes, JavaScript will render gameState into a string and join it with the string ‘gameState value: ‘ before printing it to the console.

In the second approach, JavaScript skips the step of rendering gameState into a string, and prints gameState as-is. Essentially this tells the console tool to print out two separate console logs in one line: one for the text ‘gameState value: ‘ and another for the gameState variable.

So why is the second method superior? The answer becomes obvious when gameState is a variable of any type besides a string.

If gameState were to be an array, method 2 will yield this:

And method 1 will print this instead:

This subtle different translates to a lot less wasted time. If I wanted to understand what kind of variable gameState is, I could use method 2 (the better approach) and add another component to the log like this: console.log(‘gameState value: ‘, gameState, ‘typeof: ‘, typeof gameState);, and all would be good.

Planes of existence

woman floating in water

Riding down the streets of Singapore has been great – I get to cut through static traffic and arrive earlier than car owners. But that comes at a price, and that is not something everyone readily accepts. It’s understandable – death or permanent injury are hardly palatable risks.

I thought about this for a while. Recently, over lunch with my classmates from General Assembly, I jokingly remarked that while I get to filter to the frontline of a red light like water percolating to the bottom of a vase, I’m paying for that privilege with my personal safety. It’s hard to deny that truth.

Also, without putting something like that on the line I think I would have been the victim of a lot more verbal abuse from other drivers. “Why should he get to cut through traffic like that while I’m stuck here?” is how I imagine it would go down.

I bring this up to illustrate a pattern that I’m beginning to see – life operates on multiple planes.

As a motorist, before I hit the tar, I have to fully accept the risks involved with riding on two wheels and no exoskeleton. It’s important to acknowledge this fact, otherwise I’d be operating on a different plane while acting like I’m on this one. That divergence can rip a person apart (mentally) in no time. It’s what makes it possible for the extremely wealthy to be more miserable than the extremely poor – we need to unite our hands with mind.

I would gladly exchange safety, which I honestly believe I can mitigate with skill (despite reckless drivers), for convenience. Sometimes I find myself grinning when dismounting my bike. I’d look at my watch and, being ahead of time, slowly entertain the rhetorical question: surely the reduced time I spent on the road translates to a measurably reduction in risk?

I am happy occupying my plane at this point in my life. Yes, there’s room for improvement in many respects – no arguments there. But I’m genuinely happy for what I have now, while continuing to strive for progress.

The worst thing one can do is be a sort of honorary member of a plane. Few things cause more misery than envy. Do or don’t – it’s not worth living in suspension.

(Image: averie woodard)

Alfred and other apps for the programmer

relaxing in a pool by snow mountains
Tools conserve cognitive resources for the actual tasks! Image: Robson Morgan

I now recall that about a year ago, I was introduced to the productivity app called Alfred. I tried it but couldn’t understand why anyone found it useful, and swiftly proceeded to uninstall it within the week.

I learned about the Alfred app listening to Tim Ferriss interview a man named Noah Kagan on his podcast. Noah has had an illustrious career spanning the early days at Facebook and Mint.com, and he eventually founded his own tech company, SumoMe. He is now one of hundreds of interviewees on the Tim Ferriss Show podcast, one of my favourite podcasts of all time.

But I’m not going to talk about podcasts here; I want to talk about the tremendous quality and quantity of tools that are available out there on the world wide web at our disposal.

Let’s do a stock take right now. Since I began attending classes at General Assembly two weeks ago, I’ve downloaded a number of tools that purport to make my life better (as a programmer):

  • Atom code editor
  • Atom external packages: JSLinter, Emmet, highlight-selected, standard-formatter
  • Dash offline documentation dashboard
  • Slack app for team/community chats
  • ColorZilla extension for Chrome
  • Alfred app

In two weeks I’ve downloaded these and more, and they’ve been quite helpful in specific ways.

Atom code editor has integration with my command line and Git, so whenever there are “uncommitted” changes in my code files I can see them at a glance.

The various external packages are even more powerful. JSLinter constantly reads my JavaScript file for missing semicolons, undefined variables that are meant to be defined, functions defined that haven’t been used anywhere in the code, and more. Emmet is the most beautiful implementation of an open source tool I’ve come across so far, replacing this:

With this:

With Emmet, 12 lines of HTML can be generated with one sentence. A simple tab will expand the sentence into all that HTML. The time savings is enormous.

Another tool I’m already starting to fall for is Dash. It allows me to continue to code with reference to official documentation while I’m disconnected from the internet. Talk about liberating.

A guy—I think is called Jensen—who works at ThoughtWorks introduced it to us two days ago, and I’d already found a use for it yesterday. At 7am, alone at a Subway store in Marina Square that wasn’t even open, I was working on a project and needed to refer to the Emmet documentation—to generate 100 spans with unique IDs—but had no access to the internet. Dash came in extremely handy.

Today I’m going to bring Alfred for a test drive. If I don’t feel compelled to uninstall it by the end of the day, I think it’ll join my rapidly growing repertoire of tools. It’s amazing that all these are available for free. I couldn’t be happier. Maybe one day I’ll pay my debt to the community by working on an open source tool…

Programming is an exercise of freedom

Projects that I’m used to working on are entrenched in structures (as in structure versus agency) that inevitably hold me back from full expression.

Say I’m trying to run an environmental awareness campaign. To pull it off I’d need to bend to the rules, protocols of the organisations that we have to partner, and even whims and vagaries of disgruntled bosses. To comply with these is crucial not just for the success of the project, it is fundamental to even have a project to talk about and work on. So no funny business.

When it comes to software, there is a lot more space for movement and expression. Sure, the technologies and frameworks that have been widely adopted set all new programmers down particular paths, but the beauty of programming is that you can choose to ignore all of it and still build something useful. The core utilities are open to appropriation however you like – nobody can stop you.

(Besides, whoever came up with the idea that everything you do has to be useful (usually in the narrow sense of bringing convenience or other kinds of profit) must be a really boring person.)

screenshot of rattyduck's interactive website
Rattyduck, our instructor’s friend, coded this. It’s fun and feels like a work of art!

Consider this with the fact that software has very little overhead to create and deploy (compared to other kinds of projects); it’s enough to make me walk with a skip in my feet, that’s for sure.

Programmers have the magical ability to conjure something useful out of nothing. How fascinating!

Substantial juxtaposition in Keong Saik

To juxtapose elements in a scene against others is to pick on contrasts. In Duxton where I’m having programming classes, the contrast is stark at every corner: newly erected skyscrapers behind two-storey shophouses that have stood since Singapore was a British colony; adults, mostly corporate workers, walk around the old streets dressed in clothes that are up to date.

When we get into the frame of mind of juxtaposition, contrasts are highlighted in our minds, and we marvel at how things came to be. Today, as I rode down the gentrified Keong Saik Road in Duxton, it dawned on me that Singapore underwent some dramatic transformation since independence 50 years ago.

keong saik road singapore
Keong Saik Road, Singapore

Perhaps our government planners decided it would create just this effect of juxtaposition that they splurged on the mega Housing Development Board project The Pinnacles @ Duxton. It worked on me!

Here’s the thing: manufacturing juxtaposition, with buildings as an example, can reek of pretence if the whole was not true. I’m reminded of scenes in variegated Chinese cities that have giant skyscrapers next to poverty stricken neighbourhoods.

The Duxton HDB project doesn’t give off that vibe because as a whole, Singapore is really high up on the totem pole of development after years of hard work and strategic governance. Instead, when I see the giant among dwarfs in Duxton I see a symbol of how far we have come. HDB, itself at the pinnacle of government agencies providing public housing, shines through the juxtaposition. Substance exists in the contrast.

I don’t know why exactly, but I’m feeling slight–just slightly–proud of the sight.

How programmers work together from every part of the world

The label ‘digital nomad’ exists because people whose job was to write programmes have become so fluid in the workplace that they can work from virtually anywhere in the world on the single, simple condition that there is an internet connection.

With Dropbox as ubiquitous as it is nowadays, it might be easy to overlook just how difficult it is for multiple ‘devs’ (short for developer) to work on a single project at the same time. But think about it: what happens when your friend works on the same Word document on Dropbox as you are right now, and saves her file?

Conflict, right? Dropbox’s programme will detect the conflicts and automatically save one copy—your friend’s or your copy, depending on circumstances—as a “conflicted copy”, for you to sort out later and merge them manually.

Programmers, being programmers, use a much more sophisticated versioning protocol and software. It’s called Git (pronounced as ‘geet’)- and it is the utility that empowers programmers to work remotely with one another. It is also the single biggest enabler of the open source movement. Here, I’m going to go into the technicalities for a bit so if you’re not interested in that kind of thing, feel free to drop out now!

Git is a version management software that handles the complex distributed workflow of distributed teams. While it’s powerful, it is also quite difficult to grasp at the beginning. But as with any tool, once you understand how to use it, life becomes much less burdensome.

Every web project has many files, sorted into various folders like ‘css’, ‘javascript’, and ‘images’. This isn’t far from the projects most of us are already used to. What’s different is the fact that in a file that contains code, like ‘main.js’, which contains JavaScript code, lines are linked to one another through what is written.

If someone makes changes from line 12-20, that change might have a ripple effect on every other line, and if this is not updated in the second programmer’s computer in time, and the programmer starts to work on the now-outdated version of the project, things can get chaotic very quickly. Bugs will crawl throughout the programme…

That’s one of the many situations where Git saves the day. Let’s say I’m the first programmer mentioned above:

I would execute the above commands (each line being one) in my command line interface (Terminal for Mac) to synchronise my work to the cloud. Broken down, it goes something like this:
– Save my code on my computer (cmd + s)
– Put the changed files into a figurative cart (git add .)
– Pass the cart through the cashier who will write in her logbook the message “Created resetButton function to reset game” (git commit -m …)
– Strap the cart to a rocket and launch it into the clouds. (git push origin master)

Once this is done, the latest version of our team project is on Github. Let’s say now I’m the second programmer…

The only the difference is that I now have to enter the command git pull to fetch the latest version before starting work.

What happens if programmers 1 and 2 are both working on the file at the same time, at 10:30pm on a Saturday night? This is when things can get tricky. Thankfully, Git makes the process much simpler.

Git is smart, so it will look compare the files that a programmer pushes into the repository (hosted on Github) with the ones originally in the repository, which are now outdated.

If programmer 1 finishes work first, he will push his changes to the repository without obstacles (assuming only two of them are working on the project at this time). But when programmer 2 finishes his work 30 minutes after that, a problem arises – programmer 1’s work, which did not exist in the file when programmer 2 started, is now the updated version on the repository on Github. So what happens when programmer 2 tries to send his finished work to Github?

This is the part that differentiates Dropbox from Git – instead of accepting both copies and renaming one as a ‘conflicted copy’, Git will see the discrepancy and prevent programmer 2 from being able to git push to the repository! Instead, he’s prompted to do a git pull to retrieve the latest version of the project. What happens now?

Programmer 2 now has two versions of the project. Without Git, he’d understandably be at a loss, confused over what to do. But Git knows a bit of magic – when a file has edits that are different from the one in your computer, it attempts to auto-merge them. To achieve this Git actually compares the contents of each file with one another. If the file that both programmers worked on has a total of 800 lines and programmer 1 worked on lines 1-200 and programmer 2 added lines 800-1000, Git would very likely understand that as work on two separate parts of the project and, without bothering the programmer in question, add them both to a single, merged file automatically. Isn’t that wonderful?

Of course that leaves with us a few other situations that are a little less magical. If a conflict occurs (say, Git detects that you’ve both been working on the same lines of code), what needs to be done to restore order?

I’m afraid Git can’t make decisions of which version of a block of code to retain and which to discard – that responsibility is too heavy to carry, I suppose. The programmer who receives the conflict (programmer 2 in our case, who finished his part of the work 30 minutes after his partner) must resolve the conflict manually.

That said, Git inserts markups into the file with both versions of a block of code—one that programmer 1 worked on and the other by programmer 2—that visually delineates the two versions for ease of comparison by the programmer who is doing the de-conflicting. So programmer 2 has to delete the lines of code that he knows are old, save, and upload that final copy to Github. Order will then be restored.

Is it overly complicated? At this point I’d say it isn’t. Even though I think I haven’t used half of its features, I’ve used some of the most frequently used ones and so far, it enhances my workflow as a solo programmer and on a small team that is physically close. When I eventually work on a remote assignment, I can see how Git and Github will make things smoother and make my life as a programmer slightly easier.

Quick deployment via Github Pages

Finally, I also learned about a Github feature called ‘Pages’ today. I’ve been using Codepen to do what it does so far, which is to deploy a project to the web so that it is accessible to more than just, well, my local machine.

Pages seems to offer more convenience, since deployment is executed directly from the command line rather than a web interface, but I’ll have to play around with it before giving my verdict. For now though, I like how cleanly it deploys my project online without the bells and whistles that Codepen presents by default (like the Editor view, which allows any visitor to see the source code that may taint the user experience).

Github Pages is only suitable for projects that don’t need custom server-side code!

My first game of Tic Tac Toe!

I think every aspiring programmer gets extremely excited when they create their first game. No, just me? Huh…

It’s my first weekend at General Assembly as a web development student, and as a gift, our loving instructors told us to create our first game – the classic Tic Tac Toe.

Present this task to me just a month ago and I would break out in cold sweat. This weekend was different – what a challenge! I savoured every bit of it (pun very much intended).

Here’s the pseudo-code to make a game like Tic Tac Toe for the web:

  • Create a 9-box square grid in HTML, each doing something when clicked.
  • Write a function that…
    • keeps track of turns for two players.
    • adds a “X” or “O” to a box when clicked based on whose turn it was.
    • checks every possible winning combination after every turn is over.
    • updates a sentence displayed in the browser with info about whose turn it is.
    • resets the game to the start state when reset button is clicked.

That’s more or less what is needed to put together a game like Tic Tac Toe. It is quite straightforward. Whenever I got stuck while coding, I just used pen and paper to rework the logic and write the code accordingly.

Meet Blue: my own little AI

There’s a second part to the challenge, which is rather open-ended if interpreted by an over-achiever (thankfully I’m not one). It reads, harmlessly:

Add a simple AI to support one player vs computer mode. Note that randomly selecting a space would count as “simple”. Try that and iterate from there.

Though not an over-achieving type, I set out to create the so-called “simple AI”. It took me about an hour to write the function that made a random box selection in vanilla JavaScript, and another 2 hours to integrate it into the existing 1-player game. After some restructuring, it worked.

tic tac toe game gif
A dialogue box pops up to announce the winner (doesn’t show up here)

I witnessed, for the first time, a computer programme that I created playing against me. It was beautiful. I smiled even though I was the only person in the room. A moment to savour!

This is the code that contained the “simple AI”, which probably won’t make sense to you without seeing the rest of the code:

Lines 221 to 238 made up just 17 lines of code. With JavaScript, that was enough to make a programme play a game with a user. Just imagine what we can do with 100 lines and greater depth of knowledge!

At this point I can already see that the next step is to write code that makes Blue—yes I named this AI after the one IBM nerds made that defeated the world’s number 1 chess player in 1997—play defensively. It should be able to block winning moves when a threat is detected (eg. when the opponent is one move away from victory). I haven’t quite come up with a way to do that without having to write out every possible threatening situation (when two of the same symbols are next to each other).

Then the logical next step after that is an actual AI that learns the best move. It should play defensively when threatened, and play aggressively to win when it senses no threats. Most importantly it should learn as it plays by having the ability to recognise patterns.

From here, those flags look so far away. Yet they are in sight, albeit a little fuzzy as to make me wonder if they are flags at all. But in that direction I will venture.

Just because it’s so fulfilling to have made it here!