${post.fImageName}

Building a Progressive Web App - part 2: RESTless search for a front-end framework

Missed the first post? Building a Progressive Web App - Part 1: Background and Back-end

The Office League

Time was ripe for a better name for our project than "the foosball app". With big dreams of building an online community of Foosballers, we went megalomaniac as we realized the concept could be applied to just about any "office sport". By launching the app as a service, we can enable players across "sports", companies and nations to enjoy friendly office battles!

One thing leads to another, next a concept of leagues falls into place. Anyone should be able to sign in and create a league of their own. A league should be associated with a sport, such as foosball, ping-pong, dart and who-knows-what. And so begins the history of  "The Office League" !

The fabulous world of front-end frameworks

Developers love to cut code, but history has told us this it is not always the fastest way to results. Thus, we decided to identify the frameworks out there that would fit our modern web-application requirements:

  • Routing (sending you to the right view based on url)
  • Client side rendering of pages and components
  • PWA capabilities (caching, push etc etc)
  • Testability (making it more agile and robust)
  • Performance and more..

In short, we're looking for a modern Model-View-Controller (MVC) framework running in the browser.

The developers were split into three teams, independently given the job to identify potential candidates for the job. Next, they would present their findings and declare their favorite! The following day, they would use the selected framework to implement an "Office League" prototype.

Meanwhile - in the back-end

Two developers were isolated from the rest, and given the daunting task of composing a back-end prototype for the Office League. We had been peeking at an exciting piece of technology called GraphQL, and wanted to give it a go. Maybe this could be a better solution than the traditional RESTful approach?

In short, GraphQL is a new and effective way of building http API's. It origins from Facebook and has grown very popular in little time. This is not surprising when looking at the benefits GraphQL brings to the table:

  • Fast - get exactly the data you need in a single request
  • Strongly Typed and self documenting - quickly understand the API you are using
  • Supports both read and write, a.k.a. queries and mutations
  • Language neutral, as it is based on JSON
  • Early solution for server-events a.k.a. subscriptions

Surprisingly many tools are already available, like the API browser GraphiQL and the various tools form Apollo including production grade javascript clients.

GraphiQL interface shoing query, result and documentation panels
Screenshot of GraphiQL querying "players" in the prototype API

If you are more curious about GraphQL, check out Awesome GraphQL for an extensive list of resources.

As we just had one day to create a live back-end prototype, with testing data, and had little experience with graphQL before in combination with Enonic XP, we went with the graphql-express API on Node.js and booted a server on Heroku.

Test data was retrived from the spare-time-project Foos app and placed in simple JSON files on disk. Finally all the hard work put into "collecting data" a.k.a. "playing foosball" would come in handy!

At the end of the day we had a fully functional graphQL API running, ready for the teams to use with their favorite frameworks. We already concluded that GraphQL looks like a REST-killer and will share more details on this in our upcoming posts.

Framework research

Showing logos of popular front-end frameworks
Polymer vs Angular vs Ionic vs React

In total, our three developer-teams had quickly researched four frameworks. Here is how they ranked them and why:

#1 Polymer - by Google

All three teams actually ranked Polymer as their favorite, with the following comments:

  • Installs quickly
  • Huge set of components
  • Lightweight
  • Based on Web Components
  • CSS encapsulation
  • Lots of documentation
  • PWA supporting tools

Apparently, the only downside was Polymer being less popular than Angular.


#2 Angular 2 - by Google

Ranked second amongst two teams that investigated it with the following comments:

Pros:

  • Big community
  • Uses Web Components extensively
  • Material library
  • Plus for using Typescript (as we have been using typescript for years already)
  • Fast - when loaded
  • Mobile toolkit in progress (for PWA support)

Cons:

  • Appears to be high initial loading time
  • PWA tooling is not finished yet
  • Not suited for server-side rendering


#3 Ionic Framework - by Ionic

One team looked ad Ionic and gave the following comments:

Pros:

  • Large component set and feature rich
  • Appears to be mature
  • Based on Angular and supports Web Components
  • Good community and traction

Cons:

  • Built for "hybrid" apps and using native bindings (not what we are looking for)
  • PWA support is still emerging, but Ionic could become really interesting in future versions based on their statements regarding PWA

#4 React - by Facebook

All teams looked at React, and ranked it last - or as one team put it, number 10 out of 3.

React is hugely popular these days, so one might wonder - why all these negative vibes then?:

Pros:

  • Very popular
  • Lightweight
  • Performant
  • Supports server-side rendering (isomorphic style)
  • JSX

Cons:

  • Not a framework by itself - just a piece of what you need
  • Steep learning curve
  • No component system or encapsulation
  • Requires writing CSS in Javascript
  • No PWA support
  • Licensing issues (already popular forks out there)

In short the developers argue using React will be a longer and more complex approach over the more integrated frameworks from Google. Also, the license put us off.

Frameworks in action

Three teams of developers cannot be wrong, right? Polymer was dominating in the first round. Now the gloves come off as each team gets a full day to build a prototype using their favorite framework. Only problem is, just one team will use Polymer as we need to see how the other frameworks play out as well.

As no-one wanted to use React, and Ionic was pretty much ruled out for the moment - the remaining teams set out using Angular 2 and Aurelia?!. Aurelia was suggested as interesting alternative to the other frameworks, so why not throw in a wildcard in the game?

Team Polymer

The polymer team managed to deliver a fully functional and good-looking prototype, extensively using the GraphQL api provided. The prototype provided a nice user experience handling responsive design, navigation and routing with nice url's and re-use of components across pages. Additionally the team managed to make large parts of the app support "offline" mode thanks to the PWA toolkit provided by Polymer. It should also be noted that one of the developers had some previous experience with Polymer, and also got the opportunity to put in an extra day of work.

Mobile screenshots showing listing of games and top ranking players
Screenshots from the Polymer prototype

The team points to the following benefits of Polymer:

  • Get started fast
  • Easy to learn and understand
  • Built-in web server and package builder
  • Web Components with isolation of HTML, CSS and Javascript inside the Shadow DOM
  • Big library of UI and helper components which solves complex issues such as google api components  (analytics, maps, youtube), infinite scrolling, ajax requests, offline storage, modal dialogs etc.
  • Lots of custom components made by community members
  • Common/shared CSS styles can be easily imported inside a component via style modules
  • PWA support through toolbox
  • Localization support
  • Two-way data binding
  • Support for gesture events (down, up, tap, track)
  • Super-simple event handling: specify event listeners via element attributes
  • Auto-generated documentation
  • Easy to test (tests are shipped with components)

The following was identified as negative:

  • Event communication between components might not be straightforward
  • Have to include entire WebComponents library and Polyfills
  • Examples in the official docs are not diverse enough
  • Limiated community, so there is not so much help on Stack Overflow etc.

Team Angular 2

The Angular team only consisting of two people produced a fully responsive prototype with navigation, routing, nice URLs and component re-use. Even if it required more effort than for the Polymer team, they also managed to add offline support for the Prototype. One of the developers had been experimenting with Angular for a few hours on his spare time, so that gave them a quick start.

Mobile screenshots showing lists of games and teams
Screenshot from the Angular prototype

The Angular team were impressed with the framework and how cleanly it was built. Also, the application seems performant and easily maintainable.

The team highlights the following benefits of Angular 2:

  • ES5, ES2106 compatible
  • Written in Typescript
  • Extensive use of Web Components
  • URL routing
  • Readable code
  • Data binding
  • Uses annotations
  • Easy to learn (natural and logical)
  • Dependency injection
  • Loose coupling - good for testing (toolbox generates test-skeletons)
  • Huge community
  • Toolbox - ngserve

The negative side of things are said to be:

  • A lot of files
  • Big footprint
  • Toolbox is under development

Team Aurelia

So, how did the "wildcard" team do? Unfortunately the result suffered from many smaller issues not directly related to the framework. Nasty url's (which could easily be fixed they assured),  and poorly working responsiveness was obvious. Routing appeared to be working fine. All-in-all the team only managed to produce parts of what the other teams made - in the end the most exiting part of the prototype was the name: "Foosbook" :-).

The team pointed out that Aurelia was entirely new to them, and that they lost some time initially getting installed and figuring out use of things like the http-req library.

Screenshot listing games
Screenshot from Aurelia prototype

Summarized the team highlights the following benefits of Aurelia:

  • ES5, ES2106 and typescript compatible
  • Uses Web Components
  • Full routing support
  • Easily readable code
  • MVVM approach
  • Configurable data-binding
  • Convention over configuration
  • Easy to learn
  • Testable with dependency injections

and also points out the following potential caveats:

  • Smaller eco-system compared to the alternatives
  • Commercial bindings (could also be a plus in some cases)
  • Hard to come across examples and documentation
  • No big success stories (so far)

Conclusion

The tems jointly consider Polymer as the best framework for a typical web-developer with Javascript background. Angular 2 appears to be better suited for developers coming from typed programming languages languages such as Java and C#.  This is in particular reflected by the fact that every Angular component has a Typescript class as its core, where Polymer uses an html-template definition.

The fact that Angular 2 is based on Typescript was also considered as a big plus for our team, given the fact that the Enonic XP UI has been built entirely using Typescript and we value the benefits this brings to more complex applications.

Aurelia was considered similar to Angular in many ways, but remained the outsider also after testing it.

In the end, there are striking similarities between all these frameworks when it comes to how they work and the features they provide - we believe all frameworks are of high quality and recommend you to evaluate what fits best for your project and team.

When forced to choose a framework the developers were now split right down the middle. Given the equilibrium our CTO (yours humbly) tipped the weight in favour of Angular 2 for three reasons:

* Angular is very popular so our project might be relevant to more people
* We want to learn more about Angular 2, as we are considering using it for future development of the Enonic XP UI
* The MEAN stack (A for Angular) is an alternative to Enonic XP in certain projects. Thus, adding Angular starter kits and examples to XP makes perfect sense.

We now embark on the real tasks of creating the Office League, using Angular, GraphQL and Enonic XP - or the AGE stack if you like :-).

Look forward to our next post in the series - where the data-model is established and the application interface starts to take shape.

What happens when our developers are challenged to choose a front-end framework suitable for our Progressive Web App, and at the same time to drop the RESTful approach for the new-kid-on-the-block: GraphQL? This is the second post where we share insight from our development team when building a PWA from scratch.

Continue reading »

${post.fImageName}

Building a Progressive Web App - Part 1: Background and Back-end

Native applications can deliver amazing user experiences, but at the same time building and maintaining them can be both expensive and hard. Native apps run on mobile operating systems such as iOS and Android, or desktop variants like Windows, MacOS and Linux. Developers have to build, test and distribute software for multiple different platforms, often through proprietary app-stores. Additionally they must build and maintain web-based back-end services to support them - often using an entirely different set of tools and technologies.

As users tend to stick with a limited set of trusted applications, native app adaptation is declining. The threshold for finding and installing new applications is high. Analysts predict, as much as 20% of brands will abandon their native apps by 2019 - likely replacing them with Progressive Web Apps. If you haven't tested a PWA already, check out PWA rocks.

Progressive Web Apps are made possible through a combination of several new web technologies, and marks a paradigm shift for the web - it has the potential to greatly simplify development and distribution of software.

Some things you will love about PWA's:

  • Instant loading (No install)
  • Automatically updates
  • Offline support - Yes, completely offline
  • Add web-apps to your home screen
  • Works with regular Url's and supports deep linking
  • Push notifications
  • Access to Bluetooth and other native capabilities
  • No proprietary app-stores
  • Everything else you love about the web
  • and more.

Google massively promotes PWA, and I'd recommend you to check out this video by Jake Archibald from the Google I/O Conference.

Background

Allow me to introduce myself. My name is Thomas Sigdestad, I'm Co-founder and CTO @ Enonic.

This post is the first In this series where we will take you on a journey with our development team, as we embark on a mission to create a full-blown Progressive Web App from scratch. Mixing application and content is another major issue for a lot of projects, so to raise the bar, our PWA must also provide editorial content and general marketing capabilities such as search engine optimization.

Our goal is to practically explore every relevant aspect of PWA from front-end to back-end, hit a lot of problems and hopefully come up with good and practical solutions. During this endeavour we expect to learn a great many things, and we will be sharing our discoveries through new posts on Webagility.com.

The Foosball App

To push the limits of the web we need to build a web-app that touches as many different use-cases and technical features as possible. Here are the overall requirements for the project:

  • Both developers and non-techies must be able to relate to the concept
  • Should have an interesting data model, with potentially big volumes
  • Needs to provide a relevant offline experience
  • Support storing of personal settings or data
  • Login support with popular ID providers such as Google and Facebook
  • Support User generated content
  • Provide transactions of some kind
  • Relevant use of push notifications
  • Nice URL handling and deep linking support
  • Include public facing content, for easy access and search robot indexing
  • Support localization
  • Re-useable beyond Enonic, potentially as a cloud service
  • Interaction with physical devices / IoT if possible

After some hardcore brain-twitching, we realized some of our most eager in-house developers already had a spare-time project that could be used as inspiration - an app to keep track of players and scores for Foosball. Foosball is happily played in every break - and the competition is fierce!

Two men playing Table Football in an office room
Alex and Glenn playing Foosball during a break

Turns out the potential features of a Foosball app is unlimited, and in our case - the perfect project to maximize developer engagement. At the time of writing we have identified the following features we can implement:

  • Public pages for marketing the "Foosball" service, rules, etc etc
  • Login to register new players
  • Teams, players and games would be the core datamodel - with a growing data-set
  • Notify players of upcoming games, or changes to their ranking
  • Offline support for playing and recording games
  • Deep linking into content, player statistics and game info
  • User comments on games played
  • Challenge other users for a new game

We're building the Strava of Foosball! :-)
-
Some Enonic Developer

Choosing a Back-end

As we're building a PWA, we stricktly don't have to choose a client, but we'll be focusing on using Chrome as it apparently is the most mature browser in terms of PWA.

To build the back-end of the Foosball app we will need a great many tools to deliver on the requirements:

  • Database to store the data
  • App engine to build and run the various services
  • Web server to deliver the PWA and assets
  • Basic identity handling
  • Content Management System for the marketing parts
  • Search engine to produce reports
  • In our case, everything should also be portable across clouds, including on-premise.

Facing a task like this, most teams will compose and integrate a suitable stack of tools, based on what their developers know and recommend - or what is "company standard". There are dozens of applications stacks out there from the "hip" Javascript-based MEAN stack through more established platforms such as .net, Java and the LAMP stack. Additionally we will most likely require search engine, a CMS, and an Identity system. For the search engine we could for instance use Elasticsearch. For Content Management Systems pretty much nothing is defined at the moment, which means we could do anything from a "headless" approach, via Wordpress to more advanced solutions.

In our project we're setting off with "company standard" infrastructure. The fact that we are a software company that builds this web infrastructure for a living makes it a lot more interesting. From a management perspective this is considered an excellent opportunity for dog-feeding :-)

At Enonic, our main effort is an open source platform called Enonic XP. Enonic XP provides a "stack-in-a-box" approach to web-development. Providing the essential API's required to build and deliver mission-critical web applications.
Some highlights are:

  • Javascript App Engine and web server (based on PurpleJS)
  • Embedded Storage and Search (based on Elasticsearch)
  • System for identity and role handling (pluggable with 3.rd party systems)
  • Content Studio for editorial content (supports both headless and rendered modes)
  • Built with Java and runs in any cloud

This means XP should provide the essential tools we need. Missing capabilities identified during the process will be fixed or added. We're ambitious in making XP the preferred platform for PWA projects out there.

Enonic XP can conceptually be compared to traditional OS', in that it provides everything you need to run web apps, rather than native apps. We actually refer to it as "The Web Operating System" - or WOS among friends.

Web Operating System illustration - Enonic XP logo with three round bubbles showing App Engine, noSQL Storage and Web CMS
Central components of Enonic XP - App Engine, NoSQL storage and Content Management

Enonic XP aims to simplify developent, testing, deployment, distribution, and scaling of web-apps and their back-end services. While providing freedom in choice of frameworks and clouds.

In our next blog post we will deliver a spec for the Foosball apps and choose a front-end framework...

Have you been forced to build apps for iOS and Android to stay relevant? Are you annoyed by websites pushing it's native app every time you visit? Did you ever wish you could use web-technology instead? The solution is finally here - it's called Progressive Web Apps (PWA).

Continue reading »

${post.fImageName}

5 alternatives to NodeJS for Java

Having developed software for more than 3 decades, I have used most of the popular languages out there. I was forced into coding Javascript since it's running on virtually all browsers out there. It's a very popular language nowadays and ranks pretty high on the TIOBE popularity index.

Executing JavaScript on the server is a natural thing to do, because you can then concentrate on learning one language. You can even refactor out common code that will execute both on the client and the server - this is called isomorphic code.

NodeJS is the best known and most popular engine for executing JavaScript on the server, but there are actually many ways to do this. Here are some projects worth checking out.

DIY

Lets start off hardcore, with the "Do It Yourself" approach. Developers love to create frameworks, so why should this be different? To create an alternative to NodeJS on the JVM, first you need a Javascript runtime. You definetly do not want to build the Javascript runtime from scratch. There are many Javascript-runtimes available for the JVM. The main ones are Rhino and Nashorn - both big and reasonable fast animals. Rhino is bundled with Java 7 and earlier, while Nashorn is bundled with Java 8 and later. Nashorn is the successor of Rhino and is much faster since it's using a lot of new optimization techniques.

The next thing you will need, is some sort of module system. CommonJS defines a module system, which is what NodeJS uses. It's wise to focus on that since it's basically the standard. There are several CommonJS implementations for Rhino that works pretty well. If you are using Nashorn, you will need to build this yourself since all the other implementations out there are either faulty or  simply too slow.

Next, you will probably need an http-bridge and some sort of pluggability. Then, unless you are fully NodeJS compliant, you will have to add reusable modules to make it work for your own and other's projects.

Trust me when I say, a DIY solution is a lot of work if you need something more than just running plain Javascript on the server. I have first hand experience building a NodeJS alternative in Java which you can read about later in this article. You might be better off choosing one of the existing ones below.

Vert.x

Eclipse Vert.x is a toolkit for building reactive web applications on the Java platform. It's very pluggable and speaks multiple languages - aka polyglot. That means you may freely choose your language, and JavaScript might be one of your choices. In Vert.x you have full control over the server runtime. If you are developing a web application, you actually need to create the http server in your code. 

Everything in Vert.x is reactive. That means it is non-blocking by nature, like NodeJS. This programming technique can be difficult for Java programmers, at least to switch to thinking in a reactive way. Some features are not implemented in a straight forward way in the code, so the code tends to be hard to read unless you are not used to it.

The main purpose of being reactive and non-blocking is speed. Vert.x is fast, but the speed varies between programming languages. Vert.x uses the new Nashorn for its JavaScript engine.

Vert.x is very pluggable and has a lot of existing modules. It's nicely separated into a core, language extensions and other extensions. This means that even the language support is pluggable, which is very cool indeed. 

One of the problems with Vert.x, as I see it, is that you pretty much need to implement your entire application on it. I know you can mix and match, but I found it hard to make it play nicely with my existing application. For a micro-service architecture it probably does not matter since your "glue" is the network.

RingoJS

RingoJS has been out for a while. It was one of the first JavaScript alternatives to NodeJS I looked at. I was really inspired by this project as it has a lot of NodeJS functionality out of the box. RingoJS is multi-threaded and not reactive. It's built upon the old Rhino JavaScript engine and sadly not the newer Nashorn.

Since everything in RingoJS is multi-threaded it's much easier (in my opinion) to read the examples and start programming the way you are used to. It comes at a cost, but for low to medium scale web applications it should be just fine. Web services are implemented using JSGI (JavaScript Gateway Interface) which is a standard from the CommonJS people.  Implementing web services in RingoJS is pretty simple and straight forward, very much like what Express does in NodeJS. 

There are many out of the box libraries, and there is even a package manager for downloading and managing external packages. This package manager communicates with the package portal available on packages.ringojs.org. Since Ringo supports CommonJS modules (aka require), you can probably use several existing NodeJS modules as well, but I have not tried that. Integrating with existing Java libraries is also a breeze since it's built on Rhino. Rhino has extensible support for bridging Java and JavaScript and the other way around.

If you want to use RingoJS on your own server, they provide a servlet for doing that. This means that you can dispatch requests from your existing spring application or J2EE application to some JavaScript that handles the request. 

I would really like to see it using Nashorn instead of the old Rhino. Also it seems a bit foreign for us Java developers. It feels like investing in a NodeJS replacement, instead of just an alternative.

Nodyn

Nodyn is a little different from the rest. It tries hard to implement full NodeJS compatibility - so it's actually a total replacement, not just an alternative approach. The JavaScript engine used is DynJS, which is much more performant than Rhino. Not sure how it stacks up with Nashorn since I have not seen any benchmarks on that. 

You can use Nodyn in two ways, either as a NodeJS replacement writing everything in JavaScript or embedded into your own system. Both ways of doing it, gives you excellent support for your existing Java investments. If you are using it as a NodeJS replacement, then you will load your existing Java libraries using some of the Nodyn's API's. 

The only problem I see, is the lack of servlet support. If you want to write your http web service logic in JavaScript while still working with J2EE servlets, then you are out of luck or you will need to build this yourself. Also not sure if you will ever need to replace NodeJS since it will probably never be a full blown 100% replacement anyway.

PurpleJS

PurpleJS is another alternative for NodeJS running on Java. It's one of the projects I have been working on, so I will try to be very objective when writing about it. As stated earlier there are a lot of inner workings that you have never considered when trying to create such a project. Luckily for me I had hands on experience building another framework inside a well known Web Platform, so I took all the knowledge that I had from that project, put it into PurpleJS - and improved it for the better. 

PurpleJS uses Nashorn as the JavaScript engine. Since Nashorn does not implement CommonJS module support (aka require), PurpleJS implements that in it's own way. Instead of searching the file-path it searches inside JAR files - this is the default behaviour and can be overridden. 

Implementation of JavaScript http services is pretty easy and follows the same pattern as JSGI (JavaScript Gateway Interface), even if it's not directly compatible. It also implements an express like router for request routing.  It supports http websockets support out of the box, which makes it dead easy to use. Even if it's easy to create web applications with PurpleJS, it is not limited to that - command-line applications can also be implemented using the framework.

PurpleJS is designed for rapid application development, and one of the key features is that you seldom need to reload on changes. Code is instantly refreshed if the files are changed. Executing Java code inside your JavaScript is the same as for Nashorn, but the framework hides this by providing reusable modules via it's plugin framework. Embedding PurpleJS is also very easy to do, as it provides an integration API to build integrations on. Spring and J2EE support are not there yet, but will be in the future. The default approach to PurpleJS also uses plain Maven-style modules and Gradle for building.

For now, PurpleJS uses a multi-threaded model and the http-layer is not async or reactive in itself. This can be a limitation for some, but I find it easier to build and debug applications using a more straight-forward model.

What's Next?

Now you know some alternative approaches to NodeJS. There are more, but I did not have the time to review all of them. If you want to explore the possibility to use JavaScript on the server, there are at least 4 excellent alternatives described above. I trust you to wait with developing your DIY solution until absolutely needed - and I actually bet you won't need it - ever!

NodeJS is the best known and most popular way of executing JavaScript on the server. If you have existing investments in Java and see the benefits of using the Java VM, then NodeJS might not be an ideal approach. Luckily, the JVM provides Javascript support and with it many alternatives to NodeJS.

Continue reading »

${post.fImageName}

Finding the Best Programming Font

It's four in the morning. I'm on my fourth cup of coffee. My source code is getting blurry. Where is that syntax error? Ah… there's a parenthesis that should have been closed. No wonder, it looked like the following curly bracket was the parenthesis. Perhaps if I had a different font where those two characters didn't look so similar…

And so the quest for the ideal programming font begins. Why must font previews be all about showcasing nice syntax highlighted and enlarged text? It seems like the only way to properly test a font is to try it out for several hours. I think it's about time we run some programming fonts through a visual stress test, to shake them out of their comfort zone.

(Skip to the examples) (Skip to the conclusion)

Finding candidates to test

Here are some of the resources I came across while browsing for candidates:

At this point, my alternatives were well above 100. I needed to narrow down my alternatives, but first I needed to figure out what to look for.

Establishing test criteria

A good programming font needs:

  • Monospace. While you can probably live with a variable-width font in dire situations, source code relies heavily on being able to scan/read your document vertically in columns. Most notably because of indentation. So if your i's and m's are different widths, you're gonna have a bad time. All of the fonts in this article are monospace.
  • Distinctly looking characters. So you found a nice typewriter-esque typeface? Not so fast! There are some characters that are often mistaken for another, even when using popular programming fonts:
    • Types of parentheses {([])} which may be nested to make things more difficult
    • String identifiers (programming quotes) "'` getting mixed up during concatenation
    • Commas and periods .,:; being nearly the same size
    • Characters in the shape of a vertical bar 1Il|!i¡ One time I received a password containing three such characters as a text message (shown in a regular non-programming font). Suffice to say, it did take some tries before I could login with correct credentials.
    • Similar digits and letters 0OØθB8&5S
    • Unusual whitespace characters such as non-breaking space (although this can usually be handled in your IDE by showing invisible characters)
  • Legibility. You should not have to question what characters you are reading, and text strings and comments should be easy to read. If you deal with a lot of comments and text strings in your code, it's an advantage if all glyphs look somewhat familiar to you and don't require a learning curve. Some fonts feature ligatures, which to some extent may ease legibility, but on the other hand may lead to unfamiliar glyphs, such as != being replaced by ≠.
  • Work at small sizes. In contrast to word processing which is mostly linear, programming involves a lot of non-linear reading (skipping between different sections of a document). Even though monitors keep getting higher resolutions, programmers constantly have to compromise between using a small font size to avoid too much scrolling, without causing too much eye strain from using small font sizes.
  • All necessary characters. I work in Norway, which is a country that has a couple of non-English characters in its alphabet. But we're usually in luck, since those characters are all in the basic Latin character set. In other countries, the situation may be worse and a larger number of characters may appear in text strings that you come across in the code. Another typical example: Many of the older fonts also don't have the Euro currency symbol which perhaps didn't exist at the time the font was made.
  • Weights and styles. Many IDEs use bold and italics as part of their syntax highlighting. If you use a font that comes with such weights and styles already built-in, the result is more optimized than the pseudo-bold or pseudo-italics done in your application. Especially if you're using a low resolution screen or bitmap fonts. Another argument for having multiple weights available is in order to reduce eye strain. Smaller font sizes are usually easier to read with heavier weights, while larger font sizes may need lighter weights so the result doesn't look so jarring. Also, when using inverse/night color schemes (light text on dark background), lighter weights must be used if you want to keep the same perceived stroke thickness of a font compared to regular dark text on light background.
  • Visual appeal. Sure, it's nice to have a functional font that is nice to look at as well. But that is of lesser concern in the scope of this article.

Narrowing down alternatives using functional sample texts

Too often when browsing for fonts, only a small subset of characters is shown in the preview. I decided to create my own sample text that positions similar characters next to each other and throws in a couple of extra unicode characters in there. Given the criteria I outlined above, I arrived at the following sample text:

<the quick="''""'+`${([1Il|!i¡/0OØøB8&%@~*#^>¤·→⇥¬
brown-fox:jumped.over,lazy–dogs;ÆÅ_æå–¿?27345S69¶§
‹«»›‘’“”…ACGQDEFHJKLMWNPRTUVXYZβßüéàœñçôřżłğðþ£¥€
½⅗²³⁰°©®™✓⌥⌘☞ ­αεωμγλΔΘθΩΠπплдияьъЫБЂбфФжцщш
ッシツお日大会漢字한글हकरᚼᛒᚱᚢᚾ⠚⠵⡻ينكقغشصאשמהחוז

It all started well, with grouping similar characters. But then I got a bit carried away: Latin accents, Polish, Turkish, Icelandic, Symbols, Greek, Cyrillic, cjk unified ideographs, Hebrew, Arabic, Futhark, even Devanagari and Braille. Sorry about the mess. Any curse words in there are purely coincidental.

I also wanted some pseudo code as sample text in order to get a more practical preview of each font. But instead of just writing some hello world sample code, I wanted to make a worst-case scenario. Code that really puts some stress on my retinas. So I threw together some densely packed regular expressions, fork bombs, text concatenation, and syntax errors just for fun.

$(function(){ // TOD0: fix null values
regexp=/^([\s\uFEFF\xA8])+|[\\]*$/gi;
if (!i==0&&((eval(I%20&amp;lt;1))||B%8==args[O]}{
res=(i!=Ø?'"':`<script>"#${(idS^5})"</script>'):
} else [
res=>res2?"'"+"'mm'":''--ww'+"AND ('";
exec(:(){ :|:& };:)
) return {
quiC[''k-brown"]: the.fox++,
jumped_over: lazy,dog;
this.res : res
});
}();

But still I wasn't satisfied. I've come across worse code snippets before. How could I simulate that sense of strained vision that can occur in the middle of a long coding session? Time to use Photoshop: Zoom blur. Instant four-in-the-morning-and-too-much-caffeine vision.

Analysis

Some quick notes about the images:

I made all images the same pixel width so that the text size remains consistent between each contender. I've assumed that most of you are reading this on a desktop devices, where the width of this text column is 630 pixels. The size samples are then at 1:1 scale, and the blurry code is at 1:2 scale. In other words, if you don't have a high-resolution display, open the images of the blurry code in a new tab/window. Or simply set your browser zoom to 200 percent.

Even though device pixel resolution displays are common these days, it's difficult to properly convey the exact feel of the subpixel rendering using screen shots. Therefore, I took screen shots at a traditional low resolution. If you want to know how a font looks renered on a high device pixel ratio, you'll have to try the font yourself.

All fonts are shown in regular weight and normal style. Extra weights and styles would have made this article far too long. Due to the blur effect, all the code examples appear to be of heavier weight than during regular use. All images were made directly in Photoshop in order to avoid system font character substitution (missing glyph protection). Font smoothing for outline fonts was set to Crisp, as that setting seemed to show the font hinting at its best.

The fonts are listed in alphabetical order below. Let the shoot-out begin.

 

Anka/Coder

https://fedoraproject.org/wiki/Anka_Coder_fonts

Since Anka/Coder is part of the Fedora Project, I was interested to see what it brought to the table. Time to try out my four-in-the-morning-vision filter:

AnkaCoder-b.png
Anka Coder.png

Pros: Large character set (620 glyphs). Comes with the traditional quartet of bolds and italics. Available in three widths, where the narrowest one is also the narrowest I've seen in programming fonts.

Cons: Zero 0 and uppercase Ø look exactly the same. No em-dash and en-dash. Narrower widths compress the space between the quotes, making juxtaposed single and double quotes appear nearly identical.

 

CatV 6x12 9

https://fontlibrary.org/en/font/catv-6x12-9

CatV 6x12 9-b.png
CatV 6x12 9.png

Pros: Cyrillic characters. Has a visible character for non-breaking space. Looks so 1337 that you'll need to use green or amber text color on black background.

Cons: Lacks non-English Latin characters (257 glyphs). Tiny quotes. While 1 and l look distinctly different, one of them may be interpreted as the other by accident unless you're already familiar with this font.

 

CG Mono

http://www.proggyfonts.net/cg-mono/

CG Mono-b.png
CG Mono.png

Pros: Works even at sizes below 9pt, which is impressive for a bitmap font.

Cons: Not pretty, and just with basic characters (228 glyphs)

  

Consolas

Part of the default Windows font bundle, Consolas can also be acquired when buying a copy of Microsoft Office. 

Consolas-b.png
Consolas.png

Pros: ClearType hinting. It doesn't show in the images above which were made on a Mac, but on Windows computers with low-resolution displays, Consolas really shines. Lots of characters including Greek and Cyrillic (709 glyphs).

Cons: Only regular weight and normal style. That's acceptable for bitmap fonts, but with outline fonts the competition is tougher.

 

DEC Terminal Modern

http://www.vtxemu.com/download.html

DEC Terminal Modern-b.png
DEC Terminal Modern.png

Pros: Amazing amount of characters (2218 glyphs), considering that this is a decorative font. And they are all very distinct from each other. With one exception…

Cons: The zero 0 is an oval, while the uppercase O is a rounded rectangle. Are you sure you'll remember that? Also more or less requires that you use a large font size or that you have a high-resolution display.

 

DejaVu Sans Mono

http://dejavu-fonts.org/wiki/Main_Page

DejaVu Sans Mono.png

Pros: Lots and lots of characters (3377 glyphs). Traditional look.

Cons: Less distinct characters than Ubuntu Mono, especially when it comes to the single vs. double quotes and the parenthesis vs. curly brace.

 

Gohufont

http://font.gohu.org 

Gohufont14.png
Gohufont.png

Pros: Large amount of characters (1698 glyphs in 11pt, 841 in 14pt). Not as many as UW ttyp0, but one advantage is that Gohufont doesn't need to be built from source. It works straight out of the box. Excellent character distinction. Easy to read.

Cons: Just two sizes available, although that's still twice as many than usual for bitmap fonts.

 

Hermit

https://pcaro.es/p/hermit/

Hermit-b.png
Hermit.png

Pros: Distinct characters, three weights. Wide, cyber-futuristic look.

Cons: Limited amount of characters (264 glyphs), such as lacking curly single quotes.

 

Input Mono

http://input.fontbureau.com

Input Mono-b.png
Input Mono.png

Pros: Lots of weights. Lots of widths. Italics. Large character set. The font works great on high-resolution devices. Lots of characters (922 glyphs) including Greek and Cyrillic. Input is free – for private use.

Cons: While all weights also have italics, they're just obliques (slanted, not curved). Its closest competitor Operator Mono has more beautiful true italics (but isn't free). Single and double quotes have too similar grouping, especially on narrower widths. I'd prefer if the lowercase l didn't have a serif in the bottom left corner, to make it more distinct from the one 1 and the capital I.

 

Lucida Mono EF

http://www.elsner-flake.com/

I wanted to include Monaco in this test, but since that font is only available on the Mac, it would be a bit unfair. But thankfully, Elsner+Flake have made this version (and it needs to be the EF version) which has the same prominent features as Monaco, only with slightly smaller character set and some glyph differences such as square periods/commas and dotted zero.

Lucida Mono EF-b.png
Lucida Mono EF.png

Pros: The font has a neutral/traditional look which makes it very legible and without any learning curve. All characters have been made very distinct without sacrificing legibility. I especially like the difference between single and double quotes which is visible even at tiny sizes, as well as the well-defined shape difference between {([])} which similar-looking fonts such as Consolas etc. struggle a bit more with.

Cons: Only one weight, limited amount of characters (247 glyphs) compared to similar traditional-looking programming fonts. Not the greatest difference between period and comma, although adequate.

 

Luculent

http://eastfarthing.com/luculent/

Luculent-b.png
Luculent.png

Pros: Simply the best hinting I've seen. If it looks as nice non-antialiased on Windows as it does on my Mac, you can knock Consolas off the throne as far as Windows hinting is concerned. And if for some reason the hinting doesn't work for you, you may download font files that have been optimized for specific sizes. Exceptional distinction between all characters (watch and learn, font developers!) except straight single quote (apostrophe) ' and curly single quote . Good character set size (649 glyphs), bold and real italics. Among the narrowest fonts in this test, which is practical when viewing code side-by-side such as in diff tools.

Cons: Zero 0 has a backwards slash, which made it look a bit like an 8 until I got used to it. Single quote appears a bit too far to the left, creating a half-space that sometimes looks more like a full space. The narrow character width can make Luculent look a bit heavy/dense, although this is not a problem if line height is increased and antialiasing is turned off.

 

M+ 1mn

http://mplus-fonts.osdn.jp/design.html#mplus_mn1

Mplus 1mn-b.png
M+ 1mn.png

Pros: Largest character set of any programming font I've come across (7831), and the only programming font I've found that has Chinese and Japanese characters. Post-millennial look similar to Ubuntu. Available in five weights.

Cons: Despite having Chinese and Japanese characters, Korean seems to be missing. Arabic and Hebrew characters are also missing, which would otherwise have made this a perfect multilingual font. Not the best hinting in the world, but the five weights make up for that a bit, at least on high-resolution displays. Average degree of character distinction, parenthesis and curly brace can get too similar when out of focus.

 

mononoki

https://madmalik.github.io/mononoki/

mononoki-b.png
mononoki.png

Pros: Mononoki looks so sweet and cute that I'd like to give it a hug, due to its casual and rounded look. A bit like an exaggerated Ubuntu Mono, in a good way. Excellent overall character distinction if we overlook the similar quotes.

Cons: The single and double quotes are nearly rectangular and of equal size which could potentially cause confusion when juxtaposed.

 

Nouveau IBM

http://www.dafont.com/nouveau-ibm.font

Nouveau IBM-b.png
Nouveau IBM.png

Pros: Many distinct characters (449 glyphs). Comes in two widths. High nostalgia factor from the IBM PC and Windows command console. I feel like I have to type on an old school clickety-click keyboard to do this font justice.

Cons: Uppercase I and lowercase l are too similar. That could be a deal-breaker for most of us. There's also just one weight that is quite heavy.

 

OCR A Std

This is the version of OCR A Std made by Adobe that is bundled with their Creative Suite.

OCR A Std-b.png
OCR A Std.png

Pros: Extreme distinctness between characters. Can tolerate very small sizes (8pt on low-resolution displays, 5pt on high-resolution displays). This in combination with its short height makes it very well suited for situations when you need to see lots of lines of text at the same time, for instance when reading server logs.

Cons: Machines may like OCR A, but humans will probably find it to be a bit too much form over function, as it is not very legible. The square brackets seem to grab unusually much attention. It's also a bit confusing that the 0 and the O are distinguished by their geometric shape, especially considering that the lowercase o is a rounded rectangle, but the uppercase O is not a rectangle but a diamond, while the rectangle instead is assigned to the zero 0.

 

OpenDyslexic Mono

https://opendyslexic.org

People who suffer from dyslexia often confuse characters that are mirrored copies of each other, such as b/d, p/q, n/u, m/w, d/q, p/b, f/t and so forth. This font adds a bit of depth perspective shadowing in order to alleviate some of these problems. I'm not dyslexic, so I can't tell if it makes any difference.

OpenDyslexic Mono-b.png
OpenDyslexic Mono.png

Pros: I know many programmers who have some degree of dyslexia, so kudos to the font designers for filling a need that I know is prevalent. Relatively large amount of characters (531 glyphs), although missing Greek and Cyrillic.

Cons: At smaller sizes, the distinction between parenthesis-like and vertical bar-like characters suffers quite a bit. The comma could also have been more pronounced. But at larger sizes this should work well. Just one weight.

 

Operator Mono

http://www.typography.com/fonts/operator/overview/

Operator Mono-b.png
Operator Mono.png

Pros: While not free, Hoefler & Co. prove with their Operator Mono that get what you pay for. Lots of weights and simply beautiful italics. Excellent character distinction. Works great on high-resolution displays even down to sizes below 9pt. Did I mention that the italics were beautiful?

Cons: By far the most expensive font in this shoot-out. Character count is adequate (434 glyphs), but I wish there were more Greek characters, or maybe that's just because Operator Mono visually reminds me of the caps from Adobe Lithos? Also, Input Mono may not be as stylish as this, but has both Greek and Cyrillic characters.

 

Oxygen Mono

https://fontinfo.opensuse.org/families/OxygenMono.html

Interface font made as part of the KDE Project.

Oxygen Mono-b.png
Oxygen Mono.png

Pros:  Optimized for FreeType rendering on Linux (sadly not shown in these images which were made on a Mac). Excellent character distinction, better than Ubuntu which is its closest rival on Linux.

Cons: Small character set (285 glyps) lacking em-dash and en-dash. Only one weight.

 

PragmataPro Mono

http://www.fsd.it/shop/fonts/pragmatapro/

PragmataPro Mono-b.png
PragmataPro Mono.png

Pros: Gigantic character set (6561 glyphs) that includes both Hebrew, Arabic, lots of symbols and even Braille. Good character distinction.

Cons: Not free. Rectangular single and double quotes with the same size and such similar grouping can be problematic.

 

ProFont

http://tobiasjung.name/profont/

ProFont IIx is an updated version that includes the Euro symbol.

ProFont IIx16.png
ProFont IIx.png

Pros: Works well in sizes 9 and 12, where it can even be used non-antialiased. To work well in other sizes you should be using a high-resolution display. Looks very cyber-futuristic. I like how the curly brace is of a different height than the parenthesis and square bracket.

Cons: 0 and Ø look the same. Not many characters (263 glyphs).

 

Proggy Clean Bold Punctuation

http://www.proggyfonts.net/proggy-clean-szbp/

Proggy Clean Bold Punctuation-b.png
Proggy Clean Bold Punctuation.png

Pros: The distinctness and legibility that has made the Proggy fonts popular for decades.

Cons: Limited number of characters (257 glyphs), bold quotes make them hard to read when next to each other, and bold curly brace is difficult to distinguish. Also, most modern IDEs can do syntax highlighting that makes built-in boldification in the font completely unnecessary.

 

Ubuntu Mono

http://font.ubuntu.com/

Default monospace font in Ubuntu, made by Dalton Maag.

Ubuntu Mono-b.png
Ubuntu Mono.png

Pros: Very large character set (1296 glyps) with all necessary left-to-right scripts. Good hinting that makes the font legible even at tiny sizes such as 7-8pt where eye sight becomes a bigger problem. Good character distinction without sacrificing legibility. Post-millennial visual style. Available in the traditional quartet of bolds and italics.

Cons: Not really any cons. Unless you want to be a disgruntled fanboy and dislike everything that reminds you of Ubuntu? DejaVu Sans Mono has more characters such as Arabic, but doesn't score as well on character distinction.

 

UW ttyp0

https://people.mpi-inf.mpg.de/~uwe/misc/uw-ttyp0/

UW ttyp0-15-b.png
UW ttyp0.png

Pros: The feature list of UW ttyp0 is really impressive, especially given that it is a bitmap font. Huge character set (3078 glyphs), including Greek, Cyrillic and even Hebrew. Also available in bold, and even italics in sizes 15-18pt. Lots of configuration options for different glyphs, including types of quotes and the option to have non-breaking space be shown as a toppled square bracket. Excellent character distinction.

Cons: Must be built from source. That's not a problem on Linux where it even auto compresses and installs the font for you, but to use the font on Windows or Mac you'll then need to convert the compiled BDF files using FontForge or similar tools. Reminds me a bit too much of when I wanted to try out Gentoo Linux and just gave up after compiling packages for three days.

 

Conclusion

None of the contestants in this shoot-out received a perfect score in every category. You're going to have to decide what is most important to you:

  • Generally great: Ubuntu Mono
  • Elegance and italics: Operator Mono
  • Rounded look: mononoki
  • Cyberpunk look: DEC Terminal Modern
  • Traditional look (Mac): Monaco
  • Traditional look (Windows): Consolas
  • Traditional look (Linux): DejaVu Sans Mono
  • Choice of weights, styles and widths: Input Mono
  • Number of characters: Pragmata Pro (or M+ 1mn if you need CJK unified glyphs)
  • Antialiasing agnostic: Luculent
  • Narrow width: Luculent
  • Low height: OCR A Std
  • Bitmap ease of use: Gohufont
  • Bitmap configurability: UW ttyp0
  • Dyslexia: OpenDyslexic Mono

Which font did I settle for? Well, despite all my efforts to decide on a programming font based on functional criteria, my final choice was highly based on gut feel and ignoring some of the objective data. I'm now using mononoki simply because it feels right to me. Despite the fact that it lacks many characters and the single and double quotes appear too similar. Then in a few months, maybe my font choice will change once again? Time will tell.

Feel free to share your opinions in a comment below!

A visual comparison of different programming fonts. Carefully crafted sample text with blurry worst-case scenario code. Some not so humble opinions and a conclusion you're likely to disagree with.

Continue reading »

${post.fImageName}

PurpleJS - the alternative to Node.js for Java projects

Okey, so let's say that it's not really necessary to have an alternative to Node.js, but we all do like to have alternatives right? Many many many years ago, when I was only 2^5+8. I was thinking that it would be nice to combine the power of Java and my existing investments with the simplicity of JavaScript. JavaScript makes it easy to share code between client and server so it's only natural to run JavaScript on the server too. But I wanted at the same time the power of Java and what the JVM can provide. 

With Enonic XP, the combination of Java and JavaScript is used to  speed up the development process and allow frontend developers to implement backend services. I saw that this was a very popular approach to develop software more effectively, and wanted everyone to be able to use the technology for free and in existing investments. PurpleJS was born.

What is PurpleJS?

PurpleJS is an alternative to Node.js for Java projects. PurpleJS makes it easy to build performant and lightweight Javascript server applications without the complexity of Node.js asynchronous programming model.

PurpleJS gives Javascript developers access to the vast Java community and the robustness and performance of the JVM. Java developers benefit from the simplicity and flexibility of Javascript in their projects.

Use PurpleJS when you want to:

  • code Javascript, but your application needs to run on the JVM
  • build fast and lightweight multithreaded applications with Javascript
  • create server applications with Javascript but access and use Java libraries
  • deliver isomorphic applications - running the same code on both client (i.e. browser) and server
  • build Javascript server applications that run on any infrastructure
  • code fast, no need to compile or re-deploy - especially useful for front-end projects
  • extend existing Java applications with Javascript
  • participate in the Javascript movement while leveraging your existing projects in Java

PurpleJS is a simple and capable framework for creating performant web applications without leaving Javascript. It is created in Java to give the flexibility and performance Java provides.

Getting started

I'll show you how to get started building your first web-application in PurpleJS.

You need to install two things: Java SDK and Gradle.  

Java is needed since PurpleJS is built on Java - that does not mean that you will ever need to program in Java, it's only the runtime. Gradle is a build system that is used for building applications in PurpleJS.

There are multiple ways to create a PurpleJS application, but the fastest is to use PurpleJS Boot. This is a ready-to-go server that's running Jetty and you do not need to worry about anything except your own application logic.

Setting up the project

To set up the project create a directory to hold the project files - like myapp. Go into the directory and create a file called build.gradle. This file should contain the following:

https://gist.github.com/srs/83f96a5f43ecddc4fe045d225e767a77

To test if this works, start the server by issuing the following command:

https://gist.github.com/srs/f46323314bac41cc2004632a892d0fb7

If everything works, you will see something like this:

https://gist.github.com/srs/b24435ae745d02dda1d36066020414ea

Congratulations, the project is now set up and we can start coding our application. Let's leave the application running. The system will pick up any changes so we do not need to restart the server while coding.

Main application file

If we open our browser and go to http://localhost:8080 we will see an error saying that /app/main.js is not found. This is our main entry-point for the application and it is required.

So, let's create the file src/main/resources/app/main.js and add the following:

https://gist.github.com/srs/f661826d56aa76aa2de93ceef0d05f3f

When we now refresh our browser again (http://localhost:8080), then a Hello World message appears. Simple, but this illustrates how simple it is to create a controller. You export the HTTP method that should be handled and returns the response. This response has properties like body,  contentType,  headers and status. The status is default set to 200 (OK). If we want to return JSON instead, just set a JSON-array or JSON-object to the body property.

https://gist.github.com/srs/142379437558081ac3638dd4b38015d1

The above example will output { name: 'Bill', age: 60 } with status = 200 and contentType = 'application/json'.

Request parameters

Request can contain various information. If you need to see what’s inside the request, just return the entire object as JSON like this:

https://gist.github.com/srs/91a78ad4281ad0a632e1f3a35635fa78

Let's modify main.js to implement a random generator that returns a random number between 1 and max. The max parameter should be read from max request parameter. First, we define the random number function.

https://gist.github.com/srs/8d00d03b89cdb91fa687c0b27b6e1bbc

Then we modify our exports.get function to return the random number based on a request parameter.

https://gist.github.com/srs/fdca444f4f1df0712aab79a84ab3a6e4

If we now access http://localhost:8080 without any parameters, we will get a random number between 1 and 10. Requesting http://localhost:8080?max=100 will give a random number between 1 and 100.

Routing

Sooner or later you will find yourself in need of a router. A router can route requests to different controllers and you can split your logic up into multiple files. Let's change our main.js file to include a router.

https://gist.github.com/srs/5bb43c5239c8d3a15bed3f2f97c949ae

This router can be configured by adding one or more routes. Every route can match both HTTP method and path. Let's add a route to get a random number.

https://gist.github.com/srs/05d22636e57d5d75f14735046213986a

To make this work we will need to modify our exports.get method so it delegates to the router that we have just configured.

https://gist.github.com/srs/41b99ae1a21e3b20715496c36c8299ed

If we now request http://localhost:8080 we will get a 404 since we no longer have a route on /, but on /random. Accessing http://localhost:8080/random will now give us a random number between 1 and 10.

We can also use path parameters to configure a route. If we want to access a random number between 1 and 100 using the /random/100 we can add a route like this:

https://gist.github.com/srs/3d2b968f5352c28ba2cdc50a242f83b8

If you now access http://localhost:8080/random/100 it will give you a random number between 1 and 100.

What's next?

This post is just scratching the surface of what PurpleJS can do. Want to check out what more PurpleJS can do? Please checkout the following resources:

 

 

PurpleJS is a Javascript application framework running on the Java Virtual Machine. In this post I will tell you what PurpleJS is, why it was created and how to get started.

Continue reading »

${post.fImageName}

Building software with Keynote

Gone are the days when only wand mastering Photoshop wizards could produce stunning designs. Specialized prototyping tools can now be left alone until you have that special requirement.

So - why are Google Venture and dozens of other agile companies are embracing Keynote as their favourite prototyping tool these days?

Seeing is believing

The video below shows a hands-on-Keynote-in-action-session. Watch it to learn how anyone can build an interactive prototype in just 15 minutes. Or go through the post and enjoy the video later!

Building software with Keynote: Thomas Lund Sigdestad from JavaZone on Vimeo.

 

Flat Flat Flat

Flat and minimalistic design is THE megatrend nowadays. Raning from Google's Material Design via Microsofts Universal Apps design to iOS - its all about flat - and less is more. This is good news for anyone not comfortable with handling those detailed nitty-gritty pixel-perfect effects, not to mention flat designs are easier to create with Keynote too.

materialdesign_introduction.png
Screenshot: Google Material Design

Link mode

Your average presenter tool (Keynote included) is heavily inspired by paper - yes,  the chopping down trees, boiling, pressed, square-shaped thing you can print out and give away physically. Thus the "next slide" paper-like flow, which is not exactly suitable for making interactive prototypes. Arguably going through slides is like rocket science compared to switching between files in your favourite designer tool.

As it turns out the Keynote team has yet another trick up their sleve - "Link mode". From the document settings you can change presentation type into "links only" - which will free you from the linear presentation flow. To move between slides you now have to click an object with a link - potentially taking you to a slide before the current - Crazy isn't it? I Imagine you already see the potential of this feature?

links-mode.png
Select presentation type to be "Links only"

Custom slide size

Most people are not aware, but Keynote actually supports custom slide sizes. Just choose your favourite theme, and set your preferred slides-size in pixels. This way you can easily create designs that fit perfectly on your phone for instance. You'll find this setting from the document properties tab top left.

custom-slidesizie.png
Select custom slide size from the document properties menu

Cut'n paste

"Good artists copy, great artists steal" is a famous quote. When designing in Keynote the brilliant trick is stealing good designs and ideas by copying them to make them your very own artwork.

Spend time investigating various applications, sites or design guidelines until you find something you like and steal it! No reason to invent the weel if someone has already done it before you, right? Remember you may copy just about anything - searching Google for icons is one way of doing this - i.e. "white coffee icon" shoud get you some nice white icons in a few milliseconds.

Copyright disclaimerRemember to verify permissions for any artwork before using it in live applications and sites!

Instant Alpha

As we go about copying screenshots, icons and other neat things we come across - they might not always have the proper background color to match your design. Once more Keynote has an excellent solution to your problem. To remove a color (or range of similar colors - simply select the image and use the "Instant Alpha" tool. Now select the color you want to remove (to select a color range: drag until everyhing you want to remove is selected) and release. Voila, the color is gone!

alpha.jpg
Using Keynote's Instant Alpha function you can make parts of images transparent

Magic Move

The trick where Keynote really pulls the rabbit from the hat has the matching name "Magic Move". This feature is as powerful as it is simple. When moving between two slides - objects that are similar across the slides will automagically be animated from slide 1 to slide 2. So simply copy anything that is visual in your target slide into the starting slide, select "Magic Move" as your transition type and watch the magic unfold. The result will convince just about anyone your prototype is the real thing.

magic-move.001.jpeg
Magic Move transitions the menu softly into place, while pushing the coffee cup out

Run live tests on iPhone

Since Keynote is available for iPhone too, any designs intended for use on a mobile device may easily be tranferred and run on your iPhone. Simply start the presentation on your phone and hand it over to someone and see what happens!

Useful resources

It's also good to know there are many professional design and templating sites that can help you speed up your prototyping even more - some are free - and other offer a lot for a modest contribution:

Keynote Templates

Keynotopia-Keynote-and-PowerPoint1.jpg
Keynotopia.com - Keynote templates with reusable designed components from Material Design, Windows 10 and iOS

Icons

Screen Shot 2016-09-23 at 12.09.23.png
Icomoon.io - Generate icons of any color and size. Even supports loading the most popular icon libraries too

No designer on your team? No problem! Everyone with a Mac and Keynote can create awesome interactive animated designs. This post will reveal how to rip cool designs and make them your own faster than you can say prototype!

Continue reading »

${post.fImageName}

Don't get outsmarted - code or die

Take a moment to think about why you learned to read? It’s obvious you might say, everyone should learn how to read and write. Not all of us are authors, but we still need to write to communicate and express ourselves. Back in the 14th century, most people did not see the point to read, and it was left to those who had professions that required reading.

So why code? Why can't you just leave that to the geeks, professional programmers, and those who need to code at work?

Coding has been around for centuries 

The first computer programmer, Ada Lovelace, was a poetical scientist and mathematical genius who developed an algorithm for the Babbage analytical engine.

For centuries mankind has had an interest in computer science, but not quite the computer as we think of today. If I told you that the allies won World War II thanks to computer science, would you believe me? Thanks to Alan Turing and his interest in computer science, the German's Enigma machine was decrypted. A “Turing Machine” is a model for today's computers.

“This nation should commit itself to achieving the goal, before the decade is out, of landing a man on the moon and returning him safely to the earth”

...John F. Kennedy stated in 1961. Eight years later, Niel Armstrong and Buzz Aldrin landed on the Moon. All thanks to a computer. Calculation of the flight profile was too advanced for manual work and therefore the flight profile was done by a computer. It would not be possible to land on the moon without the complexity and science behind the computer.

For years, computers were not for everyone and were also expensive. Today nearly everyone has a computer, and the phone in your pocket is actually a small computer that could calculate one million moon landings. The technology is growing exponentially. Moore’s Law indicates that computer power is doubling every second year and that we can expect a single computer to be more powerful than the brain by 2025.

Education needs to adapt 

A friend of mine was worried that technology would outsmart us. If we do not understand their language, the barrier between humans and computers will increase. To understand the computers we have to know their language.

A reality today is that some McDonald's restaurants are run by robots, and about 70% of fast food workers can be replaced. This does not have to mean that people will lose their jobs, we still need people to program and oversee the computers. Their work will change, and education needs to adapt.

More than a 100 years ago, traffic lights were humans. They have now been replaced by technology, but there are still humans who code and control the traffic lights behind the scenes.

More and more companies are redefining themselves as software companies.

We’ve gone from Blockbuster video to Netflix, bank branches are replaced with online banking. You can still rob a bank, but not in the traditional way. Bank clerks are replaced with system owners that know information technology. Banking today gives us more flexibility and safety, but we need to be on top of our game. On top of the coders game. To understand the machines we need to code, to fight internet crime we need to code.

“Everything that can be automated will be automated”, Shoshana Zuboff

Do your kid a favour, let him/her use the computer. Do yourself a favour, use the computer with your kid. I am sure you will learn a thing or two. Change in technology is not a trend that will pass.

Links:
Ada Lovelace
Babbage Analytical Engine
Apollo 11 guidance computer
Source code for Apollo 11 guidance computer
code.org
Khan Academy

Do your kid a favour, let him/her use the computer. Do yourself a favour, use the computer with your kid. I am sure you will learn a thing or two. Change in technology is not a trend that will pass.

Continue reading »

${post.fImageName}

Styling input placeholders with CSS

HTML5 and placeholders

HTML5 gave us many wonderful things. And in this case, the grass was really greener on the other side. After paddling our small HTML boat over to the grand island of HTML5 we set up camp and decided to stay, for life (or until some other even cooler island - HTML6 anyone!? - floats by).

One of many wonderful things was that we could toss out all those onfocus and onblur JavaScript combos that toggled some informative text in forms before they were filled in. Sure we had labels, and even lines of help text, but sometimes a placeholder was just right for UX and overall design (and semantics).

Old school versus new school

Remember the horrors of old? Let’s take a trip down memory lane. This is how I used to “fake” placeholders with JavaScript (true story) in the age when dragons still roamed the lands and everyone travelled by horse (a few years ago ... trust me):

<input type="text" name="mahfieldyo"
  value="A brilliant placeholder"
  onfocus="if (this.value=='A brilliant placeholder') this.value='';"
  onblur="if (this.value=='') this.value='A brilliant placeholder';"
/>
Screen Shot 2016-06-29 at 09.39.58.png
This is how my old school placeholder looked
<input type="text" name="mahfieldyo"
  placeholder="A brilliant placeholder indeed">
Screen Shot 2016-06-29 at 09.39.53.png
New school is "same same but different" (much better)

Your design task

So the story goes like this - you get a design, from a designer. And as we all know, they sometimes tend to design impossible things, things not meant for the web (damn you Photoshop). But things progress, and with time we suddenly have new super powers in CSS. Remember all those round corners about 6-7 years ago that were almost impossible before CSS3 (hello 3x3 cell tables with images in each corner)?

placeholder_design.jpg
The design versus what you can build.

You need a black semi-transparent (50%) background with a white colored text (opaque). Easy. You try the CSS' color property on the input field. Doesn't work. The placeholder will default to gray (a washed out white color). But you want it to be clear white, just like when you type text in there. You give up and cry a little bit. Fear no more. The solution is not far away!

You’d think that this really is something that is impossible. The big browser vendors sat down and said “Our way or the highway, son”, and we be all like “Yes, ok Sir, sorry for bothering you”.

But no, this is not the case this time. There is no Hersey highway you need to take. Let me show you how magically easy you can change the style of a placeholder text. Let pseudo elements (and classes) lead the way to glory and fame. But also, let vendor specific implementations hurl shots at you along the way (rest assured, we will reach the other side alive).

The code

Our new friends to get acquainted with are: ::-webkit-input-placeholder, :-moz-placeholder, ::-moz-placeholder and :-ms-input-placeholder.

To mix things up for us, they interchange between using one colon (pseudo-class) and two colons (pseudo-element) in the beginning. Because … why not?

Chrome, Safari, Opera and even Edge will listen for the webkit vendor tag, older IE (10+) for the ms vendor tag, and Firefox for the moz vendor tag. Easy peasy. So with these “tools” our design will work everywhere *.
* Not really everywhere, but close enough for me to say “everywhere” without being called a complete liar. Who cares about IE9, Firefox 3, and other legacy browsers anyways? Oh, you do?! Then I feel sorry for you (but also laughing a little bit at the same time, like when people walk into a lamp post, or they slip on a banana peel).

Let’s look at them in action. This here is them magic lines to fix it all:

::-webkit-input-placeholder {
	color: white;
}
:-moz-placeholder {
	color: white;
	opacity: 1;
}
::-moz-placeholder {
	color: white;
	opacity: 1;
}
:-ms-input-placeholder {
	color: white;
}

Not bad. That's it. Just copy pasta and give it a taste!

There are some details to explain though. Keep reading.

Vendor specifics and pitfalls

Firefox has different implementations of this spread throughout their versions, hence the almost duplicate definitions with “:” and “::” (double-colon is the latest and greatest implementation).

A catch with this code is that you cannot refactor these into one joined group in CSS, because if one browser doesn’t understand all of the lines it will ignore all of the rules in it, even the lines it does understand. So you must go for all four of them as separate groups, like in my example. Hey, don’t shoot the messenger!

Also, Mozilla’s implementation lowers the opacity of the text, so you need to “reset” it manually to get it to look just right (with opacity: 1;). After that, you’re good to go.

And of course you can be more specific than that and only change placeholder design on specific fields by prepending these pseudo classes with the class name of your choice.

Want more?

Read this brilliant Stack Overflow answer for more details about vendor support and such.

Need more tricks to fuel that CSS fire of yours? Check out how you can override that ugly yellow default background on pre-filled input fields in Chrome.

We’ve explored the deep dungeons of CSS before and found that we can access almost anything you see in your browser and shape it to your liking. But placeholder text in forms, that can’t possibly be styled, right? Right! … wrooong! Let me show you how to use CSS to make your placeholders look pretty again.

Continue reading »

${post.fImageName}

Beautify your Form with Material Design

“Once upon a time there was an Ugly Form. Every day it would look at beautiful forms residing peacefully on the endless pastures of the Internet and sigh with envy.

Don’t I deserve my share of HTML happiness?’ the Form thought.  ‘Why do users shriek in disgust every time they see me? Why do they look terrified (and sometimes cry) when filling out my fields? And why the hell do they wash their hands after clicking my flabby lifeless buttons?””

Every time I would tell this amazing fairytale to my kids before their bedtime, they’d ask me: “Daddy, but why can’t the Ugly Form be happy too? Sure, it looks like HTML got diarrhea and pooped out a pile of colorless Lego bricks, but maybe there’s a chance for it in our cruel world?

And one day I finally decided to play the Fairy Godmother to the Ugly Form and help it turn into the Kim Kardashian of forms overnight (with zero plastic surgery expenses, mind you). After some thorough research I picked Material Design Lite (MDL) as my magic wand and that’s the only thing you will need, too.

I'll get a bit ahead of myself and show you right away what will be the end result of what we're going to do in this article.  

end_result.png

Looks modern and professional, right? But it hasn't always looked like that. In fact, I wouldn't dare to show you how this form initially looked if it wasn't for the sake of this article.

Anyway, let's get to the process. To begin with, we need a web page with an ugly form. I assume you already have it, but if not - just create one and experiment with it. For this article I created a job application form for an imaginary company hiring IT specialists, see below:

https://gist.github.com/alansemenov/12e362706cc05185b9141696dea9b612

The page has some basic styling, mostly to add some padding to controls in the form, but nothing fancy. It’s totally fine if your page is already using some CSS classes. But be aware that they may cause conflicts with the MDL stylesheets, so you might want to tweak the code and remove the old classes (you can do that dynamically using the Javascript code below, too).

When you open that page in a browser, it should look something like this:

pasted-image-41.png
One Ugly Form

This form has some basic text input fields, a textarea, a table, several fieldsets with checkboxes, radio buttons and a list of bullet items. And the buttons, of course.

When I saw the ugly creature I just built with my own two hands I was like (in heavy Austrian accent): “YOU ARE ONE UGLY MOTHE**UCKER…”.

Without further ado, let’s rush to the uneasy task of turning this freak of HTML nature into something worth showing to your boss before asking for a pay raise.

First thing we need to do is add external references to the MDL’s js-library and CSS inside the <head> section of your webpage:

<!-- MDL references -->

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

<link rel="stylesheet" href=“https://code.getmdl.io/1.1.3/material.indigo-pink.min.css">

<link rel="stylesheet" href=“https://rawgit.com/MEYVN-digital/mdl-selectfield/master/mdl-selectfield.min.css">

<script defer src="https://code.getmdl.io/1.1.3/material.min.js"></script>

<script defer src="https://rawgit.com/MEYVN-digital/mdl-selectfield/master/mdl-selectfield.min.js"></script>

Alternatively, you can download the MDL package, host it on your own server and reference that instead.

Note name of the CSS file: material.indigo-pink.min.css. The “indigo-pink” part defines primary and accent colors your controls will be using. There are plenty of colors to chose from, but I picked “indigo” because it sounds mysterious and “pink” because everything beautiful is pink (for example, unicorns and €50 bills).

Now let’s create some magic. We need to write javascript code that will loop through controls on the page and apply MDL styles to them. Copy the piece of the code below and paste it inside the <head> of your page, right after the references section:

https://gist.github.com/alansemenov/6cc5fa3ff7f99c50a0a1e55073969a36

Look at the code above.

There’s a method called materializeControls which will be called in window’s onload event handler, when the DOM is in place. materializeControls calls another method called materializeTextInputs, which loops through all text inputs and textareas on the page and assigns required MDL CSS classes to them, their labels and their parent divs.

NB! In order for Material guidelines to be entirely fulfilled, each input control must be properly wrapped inside a parent div along with its label. The code will not fail if it’s not the case but "you may not be 100% satisfied with the result", as my hairdresser used to say before I had given up getting haircuts.

When you refresh the page after adding this piece of code, you will see some amazing transitions:

material_inputs-43.gif
Materialized text inputs

Note how the first three text inputs on the left and the textarea on the right are now rendered according to the Material guidelines with more air around them, labels inside placeholders and nice on-focus highlighting.

By now you are supposed to be completely hooked, like a housewife addicted to Candy Crush, and cry for more.

We will stick to the same algorithm for other controls as well.


Dropdowns

Add a new method called materializeSelects that will basically use the same formula as materializeTextInputs - going through select controls and applying MDL styles to them.

https://gist.github.com/alansemenov/bc9772e09e9d4ebc509d5552c83c65bc

The only manual thing we will have to do here is add class “mdl-selectfield—floating-label” to the wrapping div of the select element. This will make sure that a dropdown’s label is shown above the control once a value is selected.

<div class="mdl-selectfield--floating-label">

<label>Education:</label>

<select name="education">



</select>

</div>

Refresh the page to get another injection of pure magic:

material_select.gif
Materialized dropdown

Radio buttons

The code for radio buttons is a bit different because they are wrapped inside their labels (so that a mouse click on a label would select the button), but the principle is the same. Note how we apply “mdl-js-ripple-effect” class to radio buttons’ labels to achieve, well, ripple effect. You don’t have to do that but it adds an extra cool touch to user interaction with the elements.

https://gist.github.com/alansemenov/96f9ba838b18b3eab95f3bc430a81c77

material_radio.gif
Materialized radio buttons

Checkboxes

Exactly the same principle here as with radio buttons (yes, you can use the same method with arguments):

https://gist.github.com/alansemenov/d1ca576ba206757098633536668a24b4

material_check.gif
Materialized checkboxes

Tables

https://gist.github.com/alansemenov/bef8e20c305c04fcb94146ba10dac3e1

pasted-image-58.png
Materialized table

Lists

For lists (<ul> element) we will perform a little trick. To liven up the list of offices we will replace the bullet character with a “home” icon from the huge library of Material icons.

https://gist.github.com/alansemenov/1f0a8ed805b29219bb8a1b87ad89e3f8

Note how when browsing through <li> elements inside each <ul> we inject an icon before the list item’s text and then wrap both of them with a <span>:

liEl.innerHTML = "<span class='mdl-list__item-primary-content'>" +
                  "<i class='material-icons mdl-list__item-icon'>home</i>" +
                  liEl.innerText + "</span>";

In order to be able to use Material icons on your page, you need to include a reference to their font family from the Google site, but we have already done it: 

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

After that you can render any icon from the Material library like this (we used “home” as an icon Id):

<i class=“material-icons"><icon Id></i>

And that’s how our new list will look now:

pasted-image-55.png
Materialized list

Buttons

https://gist.github.com/alansemenov/25d9ee24c82eb4763fb363031a5c852d

There are many different styles and effects that can be applied to buttons; you can read about it on the MDL site. We used the same “mdl-js-ripple-effect” class to get the ripple effect whenever a button is clicked and “mdl-button—colored" class to have them colored in the primary color of our selected scheme (remember indigo?). If you replace the latter with “mdl-button—accent” the buttons will be in accent color (in our case - pink).

material_buttons-60.gif
Materialized buttons

Conclusion

Believe it or not, but we’re done. Using almost no CSS and only basic knowledge of Javascript, we turned our ugly duckling into a beautiful indigo-pink-ish swan. We could have refactored our Javascript code a little to have just one pass through all elements on the page and then dispatch processing to other methods based on element type, which would of course be much better performance-wise, but here I tried to visualize “converting” controls type by type.

And this is how our form looks after our changes:

Screen Shot 2016-06-23 at 00.26.18.png
Materialized form

For even better effect I will show you the same form “before” and “after”, side by side:

Screen Shot 2016-06-23 at 00.10.16.png
The Ugly Form before and after the changes

And here's the final source code of our now beautiful form:

https://gist.github.com/alansemenov/60927b506815ef6d129b8c59f41a7525

I hope that this article will help you to take your first steps into the beautiful land of Material Design. It’s not as scary or complicated as you may think and along the way you might even help a page or two become better versions of themselves without giving it too much effort. After all, each of us had our encounter with an ugly form even if we chose to keep it a secret.

Material Design is a hot topic nowadays. There are many who have heard of it but not so many used its guidelines in their work. It looks sexy and stuff but how do you inject all that beauty into your website? This article will explain how to apply Material Design look and feel to forms on your existing web pages using basic knowledge of JavaScript and a 3rd-party library called Material Design Lite.

Continue reading »

${post.fImageName}

Shrink your code (or die refactoring)

There’s only one occasion when you do NOT want to hear these words and that is when someone is looking at your code. Sure, you are really proud of it and it might even function properly. But do you ever wonder what another person would think of the code you write? Will they be able to grasp the monumental idea behind it without a debugger and a bottle of Jack Daniels?

I’ve worked at several software companies and each of them had different coding conventions and guidelines for their developers. Some required adding comments as often as possible, while others believed that the code in general, and naming of methods and variables in particular, must be self-explanatory.

Unfortunately, some laws are made to be broken and on so many occasions I would find myself staring helplessly at someone’s method dragging on for several screens, with a dozen nested if/else and some recursion thrown in for good measure. Code like that is as fragile as an ancient Chinese vase - even a gentle fart can break it into pieces.

My personal opinion is that a well-written class should be as readable as a page in a book.

A good author would never name characters “a” or “tmp” or “the_guy_who_constantly_puts_on_his underwear_inside_out”. The author would give them short but unique and obvious names.

And if the book has chapters, then those will not be called “Stuff”, “More stuff” or “Stuff but not the stuff from previous chapter”.

Finally, if a chapter is called “The wedding” then I guess it’s logical that the chapter would describe the wedding only and not birth, adolescence, wedding, divorce and miserable lonely death all at the same time.

Writing clean and understandable code is even more important now that the open source concept has become so popular. Having done a great deal of code reviews over the last few years, I started noticing some common patterns in the mistakes that developers tend to make. Here are a few of them, followed by my humble suggestions on how to improve on those.


1. Too long method/function that does several different things at once


Rule of thumb - function should have one and only one purpose (it’s fine to call other methods from more complex ones like constructors, of course). If it does several things, then it should be broken down into several methods, each correspondingly named.

If you need to create a form of visual controls, make one method for a form and a separate method for each control.

If it’s a call to a REST API, make sure you don’t handle the response in the same method - create separate handler methods.

It’s a very common mistake to have, for example, a class constructor that starts off being small and pretty but just keeps on growing as the class itself is being expanded with new features. It should always be possible to find patterns in the code (unless you are writing a program that emulates the work of our government) and extract those into separate methods.

Look at this constructor that was probably conceived as a well-meant child of some fearless developer but ended up as a fat boy bullied by other (leaner) methods:

https://gist.github.com/alansemenov/1b5b22b0e0f4502075e1

Here's the same guy after refactoring therapy (yes, only two lines of code in the constructor):

https://gist.github.com/alansemenov/1c7bd7a76457fd99ef6637e464b388c7


2. Too short or excessively long names of variables and functions


It should be instantly obvious what a method does, or a variable stores, by the name alone. No “run”. No “calculate”. No “a1”, “a2” and “a3”. For a method name, a verb + noun pair works just fine for most of the cases: calculateTotal, getAverage, setColor, saveContent.

If it’s a method in a class then you should consider it in conjunction with the class name. For example, if you have a class called TextBox then it’s ok to call its method setValue, because textBox.setValue() is very obvious.

If it’s a method that returns a boolean value, start its name with “is” or “are”: isInitialized, isNegative, areEqual etc.

Event handler? Use “on” + event name  (optionally with event target object): onButtonClick, onClose, onAfterRender.

And yes, if you have to call your function  “setValueInTheTextBoxThenSetFocusButOnlyIfValueIsNotEmpty” then your method is doing too much. Goto Problem #1.


3. Putting contents of the entire method inside an “if…” statement

https://gist.github.com/alansemenov/082f0a970e557be43eba45f71ed595ac

This is a very common and widely-used case. You want the method body to be executed only under certain conditions, so you put the entire code inside an if statement, then you have some more nested if-s inside, and finally end up with some hardly edible spaghetti code on your plate.

Basically, if there’s not much or nothing that happens in the else part of your if statement, then it makes sense to revert conditions, verify the else part first and exit the function before the main code of your method kicks in:

https://gist.github.com/alansemenov/3f19510135b7da1a9bf9d812f0f052a2

No changes? Do nothing.

Not enough rights? Tell user about it and do nothing.

None of the issues above? Save the changes and then finally do nothing.

This is also much more readable because the logic flow resembles the way our brain works (I'm referring to the "do nothing" part, of course).


4. Else/return overkill

https://gist.github.com/alansemenov/c7244698748da720cb4e1ef018d0eddd

There are several obvious issues here - the if…else… statement could’ve been replaced with a switch… case… and getLaserSwordColor should’ve been called only once with its value assigned to a local variable.

But another, not-so-obvious issue (and the one I’ve seen so many times) is that you don’t need else here at all. The main point of the ..else if.. statements is to skip verifying further conditions once the one that returns true is found. But if you exit the function (call return…) inside each if statement anyway then you won’t need else if, right?

Here’s the function doing the same thing, but in a slightly more readable way:

https://gist.github.com/alansemenov/338a9bb1e009fa86e201ed1eea5dbb02


5. Too many conditions in the same “if…” statement

https://gist.github.com/alansemenov/78920246914749f28384babb5e658aa3

Is it possible to instantly understand everything this code does? Does it look maintainable? What would you do to yourself should you be asked to make changes to this code? No wonder we, developers, are considered to be alien creatures by regular people who call us bad names like “nerds” and “wise-asses”.

So what should you do to avoid heavy conditions? Use nested if’s and extract conditions into methods with self-explanatory names and use those instead - this will make your code look much better.

If we expand the avenger class with some nicely named methods returning true/false based on characteristics of our heroes, then the piece of code above can be rewritten into something like this:

https://gist.github.com/alansemenov/d4b101c1b9e2c0b7eda0dccee6ae8faf

Wait, what?! Is it really the same method? Now this code can actually be read by a non-technical person who might even understand its purpose. Not only that, but we also implemented some of the nice practices we discussed earlier on, namely used self-explanatory method names (isMale, isOld etc.) and got rid of nasty else-s by exiting the method once it has fulfilled its purpose.

However, this kind of refactoring might shatter your godlike status in your spouse’s eyes, so use with caution.

Of course, these few suggestions are just a tip of the huge iceberg called “refactoring”, but they are very common ones. So do yourself a favor, be a nice person and keep in mind that the code you write may have to be read and maintained by other people in the future.

If you want good karma, write clean code. Turn your classes into lyrics. Make people name their kids after your variables. Have them read your code before bedtime to suddenly realize the sun is rising. And remember what they say about developers who write long functions: they are probably compensating for something.

“Oh my god, it’s so big!!!”

Continue reading »