With React, I Don’t Need to Be a Ninja Rock Star Unicorn

San Diego Comic-Con 2011 - Lego Ninja, The Conmunity - Pop Culture Geek from Los Angeles, CA, USA

Followers of my blog may remember my microservice period. There was a time I could not shut up about them. Now, several blogs and not a peep. Am I over microservices? Not by a long stretch.

For us, microservices are gravity now. I remember an interview with Billy Corgan of The Smashing Pumpkins where, when pressed about his choice of guitar strings, he answered: “I use them”. That’s how I feel about microservices – now that we live and breathe them every day, they are not exciting, they are air. The only people who get exited about air are SCUBA divers, I suppose, particularly if they are running low.

ReactJS, on the other hand, is interesting to us because we are still figuring it out. For years we were trying to have our cake and eat it too – merge the benefits of server and client side rendering. I guess my answer to ‘vanilla or chocolate ice cream’ is ‘yes please’, and with React, I can have my chocolate sundae for breakfast, lunch and dinner.

The problem with ninja rock star unicorns

The magical creature from the title is of course the sought after 10x developer. He/she knows all the modern frameworks, sometimes reads about the not so modern ones just for laughs, and thrives where others are banging their heads against their desks repeatedly.

Rock star developers not only do not shy away from frameworks with high barrier of entry such as Angular, they often write there own, even more sophisticated and intricate. Nothing wrong with that, except that you cannot hire a full team of them, and even if you could, I doubt team dynamics would be particularly great. The reality of today’s developer job market is that you will likely staff a team with great, competent and potentially passionate developers. I say potentially because in many cases their passion will depend on you as a leader and your ability to instill it.

The React connection

This is where React comes into play. Careful readers of this blog may remember my aversion to JavaScript frameworks in general. For modestly interactive sites, you can go a long way with just Node.js, Express, a templating library such as Dust.js and a sprinkle of jQuery for a good measure. However, a highly dynamic app driven by REST APIs is too much of a challenge for jQuery or vanilla JS alone. I am not saying it cannot be done, but by the same token, while you can cut your grass with box cutters, it is massively less efficient than a lawn mower. At the end of the day, you need the right tools for the right job, and that means some kind of a JavaScript library or a framework.

What kept me away from Angular for the longest time was the opinionated nature of it, and the extent to which it seeks to define your entire world. Angular is a cult – you cannot be in it part time.

“Angular is a cult – you cannot be only a part time member.”

Not an Angular cult member

I have already written about why I got attracted to React from a technical point of view. There are great things you can do with isomorphic apps when you combine great React libraries. But these are all technical reasons. The main reason I am attracted to React is its philosophy.

We are all idiots at times

Angular used to pride itself as a ‘super-heroic JavaScript framework’. Last time I checked, they removed it from the home page (although it still appears in Google searches – ironic, I know). I presume they meant that the framework itself gives you super-hero powers, not that you need to be a super-hero developer in order to use it, but sometimes I felt that way.

I am singling out Angular somewhat unfairly – most MVC JavaScript framework approach the problem by giving you tools to carefully wire up elements on the page with events, react to watched variables, surgically change styles, properties, collections and so on. Sounds great in the beginning, until you scale to a real-world application, and things become really complex.

This complexity may not be a big deal while you are in the thick of it, coding like a beast. You may be a great developer. The problem is that the moment you turn your head away from that code, you start the ‘idiot’ clock – until that time when you no longer remember how everything fits together.

Now, if you are looking at your own code and cannot figure out how it works, what are the chances another team member will? I long ago proclaimed that dumb code is good and smart code is bad. Not bad code, just straightforward, easy to understand, ‘no software patent here’ code. Your future self will be grateful, future maintainers doubly so.

React allows us to write boring code

Let me summarize the key React philosophy in one sentence:

“Something changed in my application’s state. Better re-render it.”

React in a nutshell

I cannot emphasize enough the importance of this approach. It does not say “watch 50 variables and do surgically change DOM elements and properties when something happens in one component, then cascade those surgical changes to other components also watching those components”. Behind this, of course, is React’s ingenious approach of using a virtual DOM and only updating the real DOM with the actual changes between the two. You can read about it on React’s web page.

After many years of ‘surgical’ JavaScript DOM manipulations, there is something completely counter-intuitive about ‘just re-render’ approach. It feels like it should not work. It feels wasteful to keep creating all those JavaScript objects, until you realize that they are really cheap, and that the true cost are actual DOM manipulations.

In fact, you can use this approach with any JavaScript rendering engine – Mustache, Handlebars, Dust. The only problem is – if you try the ‘something changed, re-render the component’ approach there, templates will re-render into inner HTML, and that is wasteful. It is also potentially disruptive if users are interacting with form elements you just recycled under their feet. React, on the other hand, will not do it – it will carefully update the DOM elements and properties around the form controls.

Increase velocity without increasing bug rate

The key design goal of React was to help real world projects running code in production. Developers of modern cloud applications are under constant pressure from product management to increase velocity. The same product management of course expects you to maintain quality of your apps, which is very hard. It is not hard to imagine that shortening the cycles will increase the bug rate, unless the code we write is simplified. Writing ‘surgical’, intricate code in less time is asking for trouble, but React is easy to understand. There is uniformity in its approach, a repeatability that is reassuring and easy for people who didn’t write the code originally to understand when they pick it up.

Developers take great pride in their work, and sometimes they get carried away by thinking that code is their deliverable. They are wrong. What you are delivering are user experiences, and code is just means to an end. In the future, we will just explain what we want to some more powerful Siri or Cortana and our app will come to existence. Until then, we should use whatever allows us to deliver it with high velocity but without bugs that would normally come with it.

For my team, React is just the ticket. As is often in life, YMMV.

© Dejan Glozic, 2015

Should I Build a Site or an App? Yes!

Minnesota State Capitol Woodworkers Toolbox, circa 1900, Wikimedia Commons.
Minnesota State Capitol Woodworkers Toolbox, circa 1900, Wikimedia Commons.

Yes, I know. I stopped blogging to take a desperately needed break. Then I returned only to be hit with a mountain of fresh, ‘hit the ground running’, honest to God January work that knocked the air out of my lungs and pinned me down for a while. Then an IBM colleague tried to ask me a Dust.js question, my doors were closed due to a meeting, and he found his answer in one of my blog posts.

So my blog is actually semi-useful, but it will stop being so without new content, so here is the first 2015 instalment. It is about one of my favorite hobbies – being annoyed with people being Wrong on the Internet. Judging by various discussion threads, developers are mostly preoccupied by these topics:

  1. All the reasons why AngularJS is awesome/sucks and will be the next jQuery/die in agony when 2.0 ships (if it ever ships/it will be awesome/cannot wait).
  2. Picking the right client side MVC framework (lots of people out there frozen into inaction while looking at the subtle differences of TODO app implementations in 16 different incarnations)
  3. Declaring client side single-page apps ‘the cool way’ and server side rendering ‘the old way’ of Web development

These topics are all connected, because if you subscribe to the point of view in (3), you either pray at the church of AngularJS (1) or you didn’t drink the Kool-Aid and subsequently need to pick an alternative framework (2).

Dear fellow full-stack developers and architects, that’s pure nonsense. I didn’t put an image of a toolbox at the top because @rands thinks it will nicely fit Restoration Hardware catalog. It is a metaphor of all the things we learn along the way and stash in our proverbial tool box.

Sites and apps

The boring and misleading discussion ‘server or client side apps’ has its origin in the evolution of the Web development. The Web started as a collection of linked documents with strong emphasis on indexing, search and content. Meanwhile, desktop applications were all about programming – actions, events, widgets, panes. Managing content in desktop apps was not as easy as on the Web. As a flip side, having application-like behaviour on the Web was hard to achieve at first.

When Ajax burst onto the scene, this seemed possible at last, but many Ajax apps were horrible – they broke the Back button, didn’t respect the Web, were slow to load due to tons of JavaScript (the dreaded blank page), and the less I say about hashes and hash bangs in URLs, the better.

It is 2015 now and the situation is much better (and at least one IBM Fellow concurs). Modern Ajax apps are created with more predictable structure thanks to the client side MV* frameworks such as BackboneJS, AngularJS, EmberJS etc. HTML5 pushState allows us to go back to deep linking. That still does not mean that you should use a hammer to drill a hole in the wall. Right tool for the right job.

And please don’t look at native mobile apps in envy (they talk to the server using JSON APIs only, I should do that too). They are physically installed on the devices, while your imposter SPA needs to be sent over mobile networks before anything can be seen on the screen (every bit of your overbuilt, 1MB+ worth of JavaScript fatness). Yes, I know about caching. No, your 1MB+ worth of JavaScript still needs to be parsed every time with the underpowered JavaScript engine of the mobile browser.

But I digress.

So, when do you take out site tools instead of Web app tools? There are a few easy questions to ask:

  1. Can people reach pages of your app without authenticating?
  2. Do you care about search engine optimization of those pages? (I am curious to find people who answer ‘No’ to this question)
  3. Are your pages mostly linked content with a little bit of interactivity?

If this describes your project, you would be better off writing a server-side Web app (say, using NodeJS, express and a rendering engine like Handlebars or Dust.js), with a bit of jQuery and Bootstrap with a custom theme to round things up.

Conversely, these may be the questions to ask if you think you need a single-page app:

  1. Do people need to log in in order to use my site?
  2. Do I need a lot of complex interactive behaviour with smooth transition similar to native apps?
  3. Do I expect users to spend a lot of time in my app doing something creative and/or collaborative?

What if I need both?

Most people actually need both. Your site must have a landing page, some marketing content, documentation, support – all mostly content based, open to search engine crawlers and must be quick to download (i.e. no large JS libraries please).

Then there is the walled up section where you need to log in, and then interact with stuff you created. This part is an app.

The thing is, people tend to think they need to pick an approach first, then do everything using that single approach. When site people discuss with app people on the Internet, they sound to me like Abbott and Costello’s ‘Who’s on First?’ routine. Site people want the home page to be fast, and don’t want to wait for AngularJS to download. They also don’t want content people to learn Angular to produce new pages. App people shudder at the thought of implementing all the complex interactions by constantly redrawing the entire page (sooner or later Web 1.0 is mentioned).

The thing is, they are both right and wrong at the same time. It may appear they want to have their cake and eat it too, but that is fairly easy to do. All you need to do is apply some care in how your site is structured, and give up on the ideological prejudice. Once you view server and client side techniques as mere tools in the toolbox, all kinds of opportunities open up.

Mixing and matching

The key in mixing sites and apps is your navigational structure. Where SPA people typically lose it is when they assume EVERYTHING in their app must be written in their framework of choice. This is not necessary, and most frameworks are embeddable. If you construct your site navigation using normal deep links, you can construct your navigational areas (for example, your site header) on the server and just use these links as per usual. Your ‘glue’ navigational areas should not be locked in the client side MV* component model because they will not work on the server for the content pages.

What this means is that you should not write your header as an Angular directive or a jQuery plug-in. Send it as plain HTML from the server, with some vanilla JavaScript for dynamic effects. Keep your options wide open.

For this to work well, the single page apps that are folded into this structure need to enable HTML5 mode in their routers so that you can transparently mix and match server and client side content.

Now add micro-services and stir for 10 minutes

To make things even more fun, these links can be proxied to different apps altogether if your site is constructed using micro-services. In fact, you can create a complex site that mixes server-side content with several SPAs (handled by separate micro-services). This is the ultimate in flexibility, and if you are careful, you can still maintain a single site experience for the user.

To illustrate the point, take a look at the demo I have created for the Full Stack Toronto conference last year. It is still running on Bluemix, and the source code is on GitHub. If you look at the header, it has several sections listed. They are powered by multiple micro-services (Node apps with Nginx proxy in front). It uses the UI composition technique described in one of the previous posts. The site looks like this when you click on ‘AngularJS’ link:

fsto-angular

The thing is, this page is really a single-page app folded in, and a NodeJS micro-service sends AngularJS content to the browser, where it takes over. In the page, there are two Angular ‘pages’ that are selectable with two tabs. Clicking on the tabs activates Angular router with HTML5 mode enabled. As a result, these ‘pages’ have normal URLs (‘/angular-seed/view1’ and ‘/angular-seed/view2’).

Of course, when clicking on the links in the browser, Angular router will handle them transparently, but if you bookmark the deep URL and paste in the browser address bar, the browser will now hit the server first. The NodeJS service is designed to handle all links under /angular-seed/* and will simply serve the app, allowing Angular router to take over when loaded.

The really nice thing is that Angular SPA links can sit next to links such as ‘About’ that are a plain server-side page rendered using express and Dust.js. Why wrestle with Angular when a straightforward HTML page will do?

Floor wax and dessert topping

There you go – move along, nothing to see here. There is no point in wasting time on Reddit food fights. A modern Web project needs elements of server and client side approaches because most projects have heterogeneous needs. Once you accept that, real fun begins when you realize you can share between the server and the client using a technique called ‘isomorphic apps’. We will explore these techniques in one of the future posts.

© Dejan Glozic, 2015

Design for the T-Rex Vision

T-rex_by_Lilyu

Note: In case you missed it, there is currently a chance to get a free eBook of RESS Essentials from Packt Publishing. All you need to do is check the book out at Packt Publishing web site, drop a line about the book back at the comments section of my article with your email address and enter a draw for one of the three free books. And now, back to regular programming.

As a proud owner of a rocking home theater system, I think I played Jurassic Park about a gazillion times (sorry, neighbors). There I got some essential life lessons, for example that T-Rex’s vision is based on movement – it does not see you if you don’t move. While I am still waiting to put that knowledge into actual use, it got me thinking recently about design, and the need to update and change the visuals of our Web applications.

Our microwave recently died, and we had to buy a new one. Once installed, the difference was large enough to make me very conscious about its presence in the kitchen. But a funny thing happen – after a few days of me getting used to it, I stopped seeing it. I mean, I did see it, otherwise where did I warm up my cereals in the morning? But I don’t see it – it just blends into the overall kitchen-ness around me. There’s that T-Rex vision in practice.

Recently an article by Addison Duvall – Is Cool Design Really Uncool caught my attention because it posits that new design trends get old much too soon thanks to the quick spreading via the Internet. This puts pressure on the designers to constantly chase the next trend, making them the perennial followers. Addison offers an alternative (the ‘true blue’ approach) in which a designer ‘sticks to his/her guns’ as a personal mark or style, but concedes that only a select few can actually be trend setters instead of followers. Probably due to them turning into purveyors of a ‘niche’ product and their annoying need to eat and clothe themselves, thus nudging them back into the follower crowd.

According to Mashable, Apple reported that 74% of their devices are already running iOS 7. This means that 74% of iPhone and iPad users look at flat, Retina-optimized and non-skeuomorphic designs every day (yours truly included). When I showed the examples of iOS 7 around the office when I updated to it, I got a mixed reaction, with some lovers of the old school Apple design truly shocked, and in a bad way. Not myself though – as a true Steven Spielberg disciple, I knew that it will be just a matter of time until this becomes ‘the new normal’ (whether there will be tears on my cheeks and the realization that ‘I love Big Brother’ is still moot). My vision is based on movement, and after a while, iOS 7 stopped moving and I don’t see it any more. You know what I did see? When iPad Retina arrived with iOS 6 installed and I looked at the horrible, horrible 3D everywhere (yes, I missed iPad Air by a month – on the upside, it is company-provided, so the price is right). I could not update to iOS 7 soon enough.

I guess we established that for many people (most people in fact), the only way around T-Rex vision is movement. That’s why we refresh the designs ever so often. In the words of Don Draper and his ‘Greek mentor’, the most exciting word in advertizing is ‘new’. Not ‘better’, ‘nicer’, ‘more powerful’, just ‘new’ – different, not the same old thing you have been starting at forever (well, for a year anyway, which seems like eternity in hindsight). The designs do not spoil like a (Greek) yogurt in your fridge, they just become old to us. This is not very different from my teenage daughter staring at a full closet and declaring ‘I have nothing to wear’. It is not factually true but in her teenage T-Rex eyes, the closet is empty.

OK then, so we need to keep refreshing the look of our Web apps. What does that mean in practice? Nothing good, it turns out. You would think that in a true spirit of separation of style and semantics, all you need to do is update a few CSS files and off you go.

Not so fast. You will almost certainly hit the following bummers along the way:

  1. Look is not only ‘skin deep’. In the olden days when we used Dojo/Dijit, custom widgets were made out of DOM elements (DIVs, SPANs) and then styled. This was when these widgets needed to run on IE6 (shudder). This means that updating the look means changing the DOM structure of the widgets, and the accompanied JavaScript.
  2. If the widget is reused, there is high likelihood that upstream clients have reached into the DOM and made references to these DOM nodes. Why? Because they can (there is no ‘private’ visibility in JavaScript). I really, really hate that and cannot wait for shadow DOM to become a reality. Until then, try updating one of those reused widgets and wait for the horrified upstream shrieks. Every time we moved to the new MINOR version of Dojo/Dijit, there was blood everywhere. This is no way to live.
  3. Aha, you say, but the newer way is so much better. Look at Bootstrap – it is mostly CSS, with only 8kB of minified gzipped JavaScript. Yes, I agree – the new world we live in is nicer, with native HTML elements directly styleable. Nevertheless, as we now use Boostrap 3.0, we wonder what would happen if we modify the vanilla CSS and then try to move to 4.0 when it arrives – how much work will that be? And please don’t start plugging Zurb Foundation now (as in “ooh, it has more subtle styles, it is easier to skin than Bootstrap”). I know it is nice, but in my experience, nothing is ever easy – it would just be difficult in a somewhat different way.
  4. You cannot move to the new look only partially. That’s the wonder of the new app-based, Cloud-based world that never ceases to amaze me. Yes, you can build a system out of loosely coupled services running in the Cloud, and it will work great as long as these services are giving you JSON or some other data. But if you try to assemble a composite UI, the browser is where the metaphorical rubber meets the road – woe unto you if your components are not all moved to the new look in lockstep – you will have a case of the Gryphon UI on your hands.

I wish I had some reassuring words for you, but I don’t. This is a hard problem, and it is depressing that the federated world of the Cloudy future didn’t change that complexity even a bit. In the end, everything ends up in a single browser window, and needs to match. Unless all your apps adopt something like Bootstrap, don’t change the default styles and move to the each new version diligently, you will suffer the periodic pain of re-skinning so that the T-Rexes that use your UIs can see it again (for a short while). It also helps to have sufficient control over all the moving parts so that coordinated moves can actually be made and followed through, in the way LinkedIn moved from several stacks and server side rendering to shared Dust.js templates on the client. Taking advantage of HTML5, CSS3 and shadow DOM will lessen the pain in the future by increasing separation between style and semantics, but it will never entirely diminish it.

If you think this is limited to the desktop, think again. Yes, I know that in theory you need to be visually consistent within the confines of your mobile app only, which is a much smaller world, but you also need to not look out of place after the major mobile OS update. Some apps on my iPhone caught up, some still look awkward. Facebook app was flat for a while already. Twitter is mostly content anyway, so they didn’t need to do much. Recently Dropbox app refreshed its look and is now all airy with lightweight icons and hair lines everywhere, while slate.com app is still chunky with 3D gradients (I guess they didn’t budget for frequent app refreshes). Oh, well – I guess that’s the price of doing pixel business – you need to budget for the new virtual clothes regularly.

Oh, look – my WordPress updated the Dashboard – looks so pretty, so – new!

© Dejan Glozic, 2013