PHP: Dispatch tables, an alternative to switch hell

Earlier this week I was putting together a block of code which ended turning into a switch statement with a tangled mess of long case blocks, complicated fall throughs, and ultimately became impossible to follow. Being a stand up guy, I decided to refactor the block using a technique where the case blocks are converted into anonymous functions, indexed into an associative array, and then the correct function is called depending on the value. I haven’t seen this show up too often in PHP code so I thought I’d share.

So what’s the problem?

The life of a switch statement usually starts out relatively benign, you have a few simple conditions and each block is relatively compact:

But then, the switch grows and each case becomes complicated enough that it the entire block becomes mostly unreadable: Ellipsis for effect.

At this point, its hard to reason about what’s going to happen because each case statement has presumably gotten so large and different conditions are “falling” through so the side effects are difficult to trace through.

An alternative

An alternative to using a normal switch statement is to use a dispatch table, which is basically an array of functions indexed by whatever variable you’d normally be “switching” on. The primary benefit to structuring the code this way is that you can easily reason about side effects since the only variables that can be changed are what captures the return value or anything passed by reference. In addition, since every case is a separate function its a bit easier to edit the code. So what does this look like? It’s actually pretty straightforward:

Extending from there, you could also call the function with arguments, potentially by reference, and even have all the functions be closures which capture the variables to avoid having to call with arguments.

Anyway, questions or comments always welcome.

Thoughts: Where are the mobile browser extensions?

Last week, I was putting together a Google Chrome extension for one of our clients to help debug Javascript events on a page and I started wondering why don’t we have mobile browser extensions? Unfortunately, there isn’t a simple answer but I think looking towards the desktop can help draw analogies to where we are on mobile now.

So this desktop thing?

Looking back to the desktop, arguably one of the strongest drivers of Firefox’s growth was its rich extension ecosystem. Compared to Internet Explorer, Firefox extensions were easier to develop, leveraged web technologies (XUL, JS, CSS), and offered powerful abstractions out of the box. Because of this, developers began building powerful extensions for Firefox which drove “power user” adoption and ultimately helped spur mainstream adoption. Developers built extensions like Firebug, Greasemonkey, and companies like Rapportive inside the Firefox extension ecosystem. Following Firefox, when Google Chrome launched it debuted its own even simpler extension infrastructure and eventually the Chrome Webstore to help distribute and monetize extensions.

Although largely positive, the extensions developed for Firefox and Chrome weren’t always user friendly. Between redirecting search traffic and surreptitiously injecting ads, “greyhat” extensions negatively impacted user experience while generating revenue without generating value. These “greyhat” extensions fueled what’s colloquially known as Israel’s download valley and ultimately millions of dollars in revenue.

Right so what about mobile?

Compared to the desktop, the landscape on mobile is notably different because of an Apple and Google duopoly with Apple primarily monetizing hardware and Google monetizing search advertising. Additionally, compared to the desktop, Apple and Google have an unprecedented level of control over user devices, all but ensuring that devices will arrive with either Safari or Chrome installed.

I think because of this control, Apple and Google have little incentive to open up Mobile Safari or Mobile Chrome to 3rd party extension developers since doing so would compromise the browser user experience for little gain over the competition. But what about Firefox?

Although Mozilla has released a Firefox build for Android, I think they’ve recognized that trying to win market share away from Chrome on Android is a losing battle and they’re starting to seriously pursue FirefoxOS. Because of this, I don’t think Mozilla will invest in Firefox mobile extensions since it’s clear that there’s more opportunity in powering the OS layer of a user’s phone.

Tips: Five things I’d tell my 21 year old self

Yesterday, Daum and I hung out at HackHarvard and gave a presentation about how we started Setfive, the challenges we faced, and some of the lessons we would tell our younger selves. The feedback and resulting discussion was pretty interesting so it seemed like it makes sense to share. Some of these things are probably mistakes you have to make for yourself and 90% of advice is crap.

Don’t get bullied

Looking back, a lot of the early “negotiations” I did with clients was really them pushing me around and me accepting whatever terms they ultimately demanded. People were using veiled threats of yanking the deal, asserting that “I didn’t know how business was done”, and being overly demanding with changes and calls to manipulate the direction of the deal. In addition to professionally, I also remember several instances of real estate brokers and landlords trying to strongarm me personally. Anyway, so the takeaway has been in life or work there’s a difference between negotiating and bullying.

Don’t be afraid to say “I don’t know”

During highschool and college, I’d always been conditioned that when someone asks a question, especially an “adult”, I should obviously know the answer. Professor singles you out to answer a question? Better know the answer. Unfortunately, this feeling stuck with me into the “real world” and I had a tough time admitting that I didn’t know the answer to a question on the spot. This usually resulted in overpromising, having to backpedal later, or being stuck bullshitting through some half baked explanation. After being around the block, it became clear that saying “I don’t know, let me get back to you” was acceptable and the better move. Turns out, in the real world everyone isn’t a walking manpage.

“Big” $ numbers are just numbers

Coming out of college, the largest check I had written was for $5000 and the largest check I’d probably cashed was for around the same. Because of this, I had a hard time taking myself seriously while asking for “big” dollar numbers. After a while, I started to realize everyone has a different concept of what a “big” number is. $5,000 might be a mountain of cash to me but to someone else its just their monthly Salesforce.com subscription. Once I understood this, it became much easier to walk into a meeting and confidently talk about money.

If they look clueless, they probably are

Throughout highschool and college, I hadn’t experienced many instances where someone was trying to seriously cover up the fact that they were clueless. Over in the real world though, this seemed to start happening frequently. Initially, I had a hard time wrapping my head around the fact that the “Senior Developer” explaining his “master/master” setup was just entirely wrong. The issue with having these blinders was that it made it difficult to effectively communicate with stakeholders when there was someone bollixed in between. Once I realized that cluelessness was really cluelessness, it became much easier to marginalize the people that were lost and get shit done.

Everyone is not like you

Something that took awhile to realize was that not everyone is like me. I had a hard time figuring out why everyone didn’t “get” how to use certain websites or why everyone didn’t immediately jump on new tech products. Turns out, everyone isn’t a heavy drinking software engineer that reads Hacker News. After realizing that, it became easier to emphasize with different types of users and also better connect with stakeholders.

Anyway, these are my notes to send back to 2009. Would love any thoughts or feedback in the comments.

Bitcoin: Thoughts, ideas, and opportunities

In 2009, an engineer using the pseudonym Satoshi Nakamoto introduced a new digital, open source, currency to the world called “Bitcoin”. Since then, the buzz, excitement, and adoption of bitcoins has grown at a phenomenal rate, with the total value of bitcoins in circulation hitting $1 billion as of April 2013. Talk of a bubble has coincided with the buzz, but both have also served to highlight the tremendous potential in the Bitcoin ecosystem.

Great, so what is it really?

Paraphrasing from Wikipedia:

Bitcoin is a decentralized digital currency based on an open-source, peer-to-peer internet protocol. […] Bitcoins can be exchanged through a computer or smartphone locally or internationally without an intermediate financial institution. […]

Bitcoin is not managed like typical currencies: it has no central bank or central organization. Instead, it relies on an Internet-based peer-to-peer network. The money supply is automated and given to servers or “bitcoin miners” that confirm bitcoin transactions as they add them to a decentralized and archived transaction log approximately every 10 minutes.

I’m going to butcher any explanation I try to provide but Quora has several good writeups on what Bitcoins are and how they work. A reasonable analogy though, is think about “Bitcoins” as a type of precious metal that has no intrinsic value but is able to store value, transfer value between parties, and be mined to find new pieces.

The key takeaways about how Bitcoins work are:

  • Unlike traditional currencies, no central bank controls the amount of currency in circulation. Instead, the total amount of possible Bitcoins is algorithmically limited by the protocol itself.
  • Transactions between parties are relatively anonymous and done in real time. Contrast this with other digital payments like credit cards or wire transfers where there is little anonymity and a settling period.
  • As of now, there’s absolutely no regulation as far as reporting, security, or anything else you’d associate with traditional financial institutions.
  • Currently, it’s all digital – there’s no practical way to “print” a Bitcoin and use it like a dollar bill

So what’s going to be disruptive?

There are dozens if not hundreds of startups playing in the Bitcoin space and several “large” companies have also started adopting Bitcoins as an alternative form of payment. Several high profile investors including YCombinator and Union Square Ventures have also made significant Bitcoin related invetments, signalling that savvy investors believe a potential market exists. Personally, I’m excited about companies attacking the following:

Hassle free, instant, and international money transfer. Paypal was supposed to allow us to do this, but even in 2013 its difficult and expensive to transfer people money – let alone internationally. If someone can address the current concerns of fraud and money laundering using Bitcoin they’ll have an instant winner on their hands.

Catapult in legalized online gambling. In the last few years, there’s been an ongoing discussion about if America should legalize online gambling and if so, how it should be done. Because of the decentralized, anonymous nature of Bitcoin, it’s conceivable that the emergence of a large enough Bitcoin powered gambling market would force the US government to legalize online gambling in order to get access to the additional tax revenues. This would obviously be a boon for struggling social game companies like Zynga, but also provide an enormous opportunity for new startups.

Provide a viable alternative to credit cards. Recently, there’s been a lot of action in the payments space including innovative companies like Square and Roam which are aiming to alter how consumers pay at the point of sale. Unfortunately, almost all of these new payment solutions still rely on existing credit card infrastructure to complete the payment which leaves them at the whim of interchange fees. Boston based LevelUp is tackling this issue but at the end of the day they’re still getting hit by the fees somewhere. An innovative Bitcoin company which provides a viable alternative to this existing credit card infrastructure would open the door to radical innovation in the payments space by eliminating hard interchange fees.

What might go wrong?

There’s a huge amount of opportunity in the Bitcoin space and the ecosystem is just starting to build out. With the Bitcoin boom of 2012 already inked on the Wikipedia entry, the next few months are going to be a critical time for the nascent currency. The single largest to Bitcoin is ultimately going to be regulation from sovereign governments. The US Department of Treasury has already issued several statements regarding Bitcoin and its clear the government isn’t happy with the situation as it stands now.

Regardless of what regulation is passed, Bitcoins are technologically different from previous virtual currency and the ecosystem has already demonstrated its resilience and innovation.

A modest proposal for how we can fix WordPress

Last month, a post started making the rounds on the internet decrying the dire state of the WordPress codebase. James highlights several legitimate gripes but unfortunately he muddles the discussion by mixing major problems with otherwise minor concerns. Another problem, is that James’ post considers the issues purely from a technical perspective but ultimately business concerns are going to motivate a drastic change in WordPress. Looking at James’ post and from my own run ins with WordPress, the biggest problems with WordPress as it exists now are:

Broken data model: As James pointed out, as people have started to use WordPress like a CMS with by adding things like custom post types and plugins it’s clear that the underlying data model is too rigid to properly support this need. The result of this, is that developing custom database functionality is notably difficult and it limits the types of extensions that can be built purely inside WordPress.

Limited separation of concerns: Throughout WordPress, globals are heavily used, templates are free to interact with the database, and there’s generally no concept of MVC separation. Apart from being confusing, this makes it difficult to effectively reason about the behavior of a WordPress install, making “smart” caching impossible. Additionally, it makes it difficult for dedicated “frontend” developers to work on templating since they’re often left juggling PHP code. Both of these issues ultimately make running a WordPress site more expensive since you’ll need more resources for operations and development.

No OO/Encapsulation, No Namespaces, No API: Owing to its PHP4+ heritage, the core WordPress code is entirely procedural and because of this every function touches the global namespace. Also, WordPress doesn’t have native support for serving as an API backend and exposing its data in different formats or interacting with non-browser clients. The OO and namespace issue is largely technical but it makes it difficult to develop modular WP components or mixin off the shelf PHP packages. The lack of a robust API makes it impossible to use a single WordPress installation to serve content on the web but also serve as a service for mobile clients, which ultimately limits its utility.

So how do we fix it?

“Fixing” an application as large as WordPress is obviously a herculean undertaking, especially because of the need to balance the existing ecosystem with the need for a clean, strong foundation. The reality is that modernizing WordPress is ultimately going to require a full rewrite but I think it could be strategically orchestrated to win community support for the backwards compatability breaks.

Without further ado, here’s how I would do it:

June ’13 – Release Twig for WordPress

Twig for WordPress is a fully featured implementation of the Twig templating engine for WordPress. It allows developers to write WordPress themes in Twig instead of mixing PHP and HTML. Along with Twig, the plugin includes modern template caching techniques like partial page rebuilds and ESI support. In order to leverage Twig and its related benefits, developers have to write their themes with reasonably strict View/Controller separation since variables must be explicitly passed to Twig templates.

Theme designers are initially hesitant but once they see how much easier tracing the structure of Twig templates is versus straight PHP they’re converts. Developers are also fans since they enjoy being able to make the necessary page variables available in a template and then hand pages off to be themed. Benchmarks are done. Hackathons are sponsored. Themes are converted to Twig.

September ’13 – Release Doctrine Power Tools (DPT)

Leveraging Doctrine2, DPT enhances WordPress by augmenting it with the Doctrine2 ORM and associated “power tools”. This allows developers to seamlessly create new MySQL tables and then automatically generate administration CRUD for those tables. In addition, custom plugin code can choose to leverage Doctrine2 to interact with the new tables. With DPT, WordPress administrators are also able to design custom forms to insert data into custom tables and then filter and export the data in these tables.

Developers familiar with ORMs are immediately excited and after they try it out they’re hooked. They start evangelizing DPT in the community because it takes the drudgery out of creating custom database functionality in WordPress. Enterprise users slowly get wind of it and adopt it as well since it empowers their marketing team to do more without involving developers. WordPress has an ORM. Everything isn’t being stuffed into wp_posts.

January ’14 – Release WP Paladin Alpha

WP Paladin is a PHP 5.3+ object oriented rewrite of WordPress with an additional “compatibility layer” which provides compatible legacy plugins and themes access to the normal WordPress API. From a user perspective, Paladin has the same installation procedure, Admin UI, and basic functionality as stock WordPress. Additionally, a handful of the most popular plugins have been ported to be 100% compatible with Paladin. Technically, WP Paladin shares several key Symfony2 components with Drupal 8, notably the HttpKernel, which allows interoperability with other apps using HttpKernel. It also supports Twig templating and ships with the Doctrine2 ORM and DPT.

Since Twig for WP was released in June ’13, dozens of Twig themes have become available and early adopters are eagerly experimenting with Paladin. Although it currently only supports a handful of traditional WordPress plugins, it’s faster, easier to develop on, and plays well with others. The excitement is palpable. Blog posts are written. SXSW tickets are bought.

March ’14 – Release WP Paladin Beta

WP Paladin Beta is similar to the initial release except the “compatibility layer” has been removed, critical bugs have been fixed, and the platform is significantly more stable. The beta version is launched at an exclusive SXSW party to a frenzied mob. It’s taken a little less than a year, but the WordPress codebase has been modernized and new features have added. Additionally, the most popular WordPress themes and plugins have been ported to be compatible with the Paladin codebase.

The download counter hits 1 million by the end of SXSW. Congratulations are in order. VC Money is raised.

Great, count me in!

Doing something like this would certainly be a great way to “earn your stripes” but ultimately it’s going to end up burning thousands of man hours for an unknown payoff.

But who knows, maybe a company with deep pockets, talented engineers, and a disposition for risk will give it the ole college try.