Kotlin: Three Reasons To Start Using It Today

Kotlin: Three Reasons To Start Using It Today

With the announcement at Google I/O 2017 that the Kotlin programming language will be officially supported as a first class citizen for the Android framework, there’s been a lot of talk around what Kotlin is and how it compares to Java. This post highlights the reasons why our development team at Shockoe feels that Kotlin is the wave of the future and why Android developers should start adopting it.

What is Kotlin?

Kotlin is a statically typed programming language that runs on the Java Virtual Machine (JVM). It’s a multi paradigm language that contains elements of object-oriented programming that you’d see in languages like Java and elements of functional programming like what you’d find in JavaScript.

Why should you start using Kotlin?

Here are our top three reasons why you should jump in:

#1 Easily integrated into your mobile stack

Kotlin code is compiled into the same bytecode that your regular Java programs are and uses the Java Virtual Machine (JVM) to execute that code.
This means that Kotlin still has access to all the same libraries and frameworks available to you in the Java world with the addition of those from the Kotlin standard library. This also allows Kotlin and Java code to run concurrently with one another. Java classes calling methods in Kotlin classes or libraries and vice versa. This can even be done in the same file. Take this example from a library that handles unit conversion:

Here we have a function that takes a Double parameter and returns an Int. However, we want to use the java.lang.Math class to round as this feature doesn’t exist in Kotlin. So we round to the nearest place and call a method from the Kotlin Double class to convert the result into an Int.

This duality of execution allows developers to easily convert their existing Android projects from Java to Kotlin or to simply add new features written in Kotlin, without converting previously written code.

Additionally, Kotlin has an option to compile into JavaScript which is compatible with the standard JavaScript specifications like Asynchronous Module Definition (AMD), CommonJS, and Universal Model Definition (UMD). This allows developers to share code written in Kotlin to other environments like Node.js or even to cross platform environments like to Appcelerator’s Titanium framework.

#2 Multi-paradigm language

A lot of the developers from Shockoe come from multiple different backgrounds. Some started with Java and transitioned into writing JavaScript while others started with JavaScript and have since learned about other languages.

Kotlin adds a lot of functional features to the object-oriented nature of Java. I realize that Java 8/9 adds similar features but this post is specific to the Android platform.

These features coupled with improved/sugar syntax lead to a much more easily read codebase. I won’t go over all the features but some of the most prominent ones are higher order functions, null safety, better typing with type inference, and much less boilerplate code.

These features, in particular, allow a developer to write much cleaner code and a lot less of it. Here’s an example of some Java code to perform and common action – filtering a list:

This isn’t too terribly much but it can quickly spiral out of control as you start adding more complexity. The Kotlin equivalent would look like:

Yep, that’s it. There are many more operators that can be appended to the end of that, for instance if you wanted to map the results to strings and return the string list you just make one minor change.

#3 Official Support From Google

No brainer here, right? However, the announcement from Google I/O 2017 is a huge deal for the language. In addition to the benefits of Kotlin over Java such as those detailed above, Kotlin will now have full support in Android Studio and within the Android ecosystem. JetBrains and Google are working together to continue to support the language into the foreseeable future.

Kotlin is by no means meant to replace Java. However, it will allow for better apps to be written using a much more modern and architected language that keeps developers in mind.

Conclusion

Now is a great time to jump into Kotlin and to start writing your Android apps with it. It will lead to better productivity for your mobile team, as they’ll be writing less code – which will be more readable and therefore easier to maintain.

Additionally, if you’re a multi-platform development team, the cross compilation into JavaScript is a great addition as you can easily create tools that work within frameworks for both languages.

Then there’s also the similarities between Kotlin and Swift as is highlighted here. This helps  bridge the gap between iOS and Android development teams.

Additional Resources

Official Kotlin Documentation

Sample Kotlin App

Kotlin Android (Layout) Extensions

Anko – Library with many Kotlin helper tools for Android

Kovenant – Promises for Kotlin

Metalling with Titanium: Building my first Alloy application

Metalling with Titanium: Building my first Alloy application

 

Event listeners. Callback functions. Asynchronous programming? These words were foreign to me when I first started working at Shockoe LLC the first week of October 2015. But somehow, I needed to use these things to create a mobile application in the next two months.

I wasn’t completely new to programming. I had recently taking Java programming courses and was learning other languages like C++ and C# by watching online tutorials. Before I started working at Shockoe, I was told to learn JavaScript as that was predominately what I would be using to create Titanium Alloy applications. Going through the tutorial on CodeAcademy taught me little about the language. It seemed to be mostly a tutorial on what programming was. But I figured that since I had the gist of programming, I wouldn’t have much of an issue as anything could be solved with a simple Google query.

Showing up to work on the first day taught me that that wasn’t the case. Edwin, the CEO at Shockoe, assigned me to work on Fighting Mongooses, a name with which I’m now beginning to understand the logic behind.

The concept behind the app sounded pretty simple but integrating various devices, a server, a database, and mobile OS’s turned out to be far more complex than I had anticipated.

The first week or two was spent just trying to figure out what was actually happening in this partially built application.  I slowly started to figure out what the different pieces of code were doing to understand the logic. I used what was already available to piece together a rudimentary working application to fulfill the initial requirements and to prove I could fit in at Shockoe.

From there, I slowly expanded the capabilities of the application and learned more about Appcelerator, Titanium, and JavaScript along the way. After a month and a half of working on Fighting Mongoose, it has taken on a bit of my own personality. It is no longer another developer’s application that I was given to complete and that is a great feeling.

There is still a lot that I need to learn to get near the level of the other developers here, but I have had some great guidance and help while working on the Fighting Mongooses project.

I still have much that I wish to accomplish with the application and feel more comfortable and confident each day with what I’m doing.

I recently found an old version of the app on a device I used for testing about a month ago and it’s amazing to see for myself the progress that I have made since.

I look forward to see the kind of progress I can make in the next month on onward here at Shockoe.

 

 

Node.js – Storing data with MongoDB

Node.js – Storing data with MongoDB

The last few weeks we have focused on web service design using Node.js with Express. So far we have covered getting started with express, using EJS to create web pages, and creating a push notification server. Today we will go over how to save data on your node project by using MongoDB.

This post will assume that you have MongoDB installed on your machine already. Check out the MongoDB Installation page if you do not have it setup.

First, let’s go over MongoDB a bit. MongoDB is a document oriented database. This allows you to just shove whatever JSON you want into it. You don’t have to declare a table structure like you do in SQL. You don’t even need to declare your collections at all. If you try to use a collection that doesn’t exist it just gets made for you immediately. Documents are stored in collections that you define, but documents within a collection don’t have to be similar at all. MongoDB also features an amazing query system. Imagine we want to store information about fruit. We could do the following:

We now have a fruit collection containing one fruit: an apple. Let’s add a few more:

Now we have a strawberry and an orange in our fruit collection. To get all fruits in our collection that come from trees we would do:

If we wanted to find all fruits that are red we would do:

And to find all fruits that are yellow or orange we would do:

Now apples can be green too. Let’s modify our apple entry to reflect that:

There are a few interesting things to be aware of when updating a document. By default, mongodb will only update the first entry it finds. You can set the multi option to force it to update every entry that matches the query. Also, note the $push operator I have included in the update object. That is telling mongo it will be adding an entry to an array on the document. If you left off push and just did:

You would be very disappointed. Setting no update operator will replace the document completely:

So what if you wanted to update a field that isn’t an array? You use the $set update operator:

MongoDB is very powerful and an excellent document store, but it lacks the join power that SQL brings to the table. You can join documents together by their _id field using MonoDB’s populate, but it’s not nearly as fast as what you can do with a few SQL joins. I encourage you to explore MongoDB as an option for your databases, but it’s important to approach your database design differently with MongoDB than with SQL. Be sure to check out the documentation for all you can do with MongoDB.

So how to we start using Mongo with Node? There are several libraries available on npm for connecting to Mongo, but I will be focusing on Mongoskin and Mongoose.

Let’s go ahead and get Mongoskin out of the way. Mongoskin is what you want if you just want to run basic MongoDB commands and nothing more. To get started add Mongoskin as a dependency:

And then in node:

Mongoskin is very easy to use and most MongoDB commands are supported. It has its issues, but if you want something simple to connect to a mongo database look no further. If you want the best MongoDB experience you can find with Node, keep reading!

On to Mongoose. As they say on their website: “Mongoose provides a straight-forward, schema-based solution to modeling your application data and includes built-in type casting, validation, query building, business logic hooks and more, out of the box.” Mongoose is a delight. To get started add Mongoose as a dependency:

It’s nice that MongoDB doesn’t need to have schemas, but it’s great that Mongoose gives them to you. Let’s put together a schema for our fruit collection:

Most of the schema above should be straight forward. Name must be a string or Mongoose will remove the property from the object before using it as a model. Color must be an array of strings. Source must be a string, and if it’s not present Mongoose will automatically set it to “tree”. Default values will not get stored in the actual database, but they will be applied when Mongoose pulls them out. The virtual “numberOfColors” will add a property automatically. Virtuals are great for properties that can be calculated based on the existing data on the model.

To use the fruits model:

The examples above barely scrape the surface of what you can do with MongoDB and Mongoose. Do yourself a favor and explore the possibilities of a document oriented database backed by MongoDB.

Creating Dynamic Web Pages with EJS

Creating Dynamic Web Pages with EJS

    If you have been following along with our series on how to create your own web server, you should now be familiar with node.js and Express.  Node.js lays the groundwork for the web server and Express builds upon it.  If you haven’t already, I recommend that you take a look at the previous blog posts on Node.js and Express before we get started.

    The next step in building an awesome web server, is using EJS to render dynamic web pages with embedded JavaScript.  You can check out the EJS home page to view more documentation.  After your Express project has been set up, take a look at the app.js file.  In this file, you will see the line:

    This use statement means that when you visit your project in a web browser, Express will look in the routes folder for a file called index.js that will tell the browser what to do.  Right now, the index.js file should look something like this:

    Right now, the Express router has one interaction that will render the home page.  Currently, when there is a GET request to the route ‘/‘, Express will render the view found in views/index.ejs.  The first argument for the render function is the name of the view file, and the second is an object that will be passed to the view file when it is rendered.  This object can be used by EJS to change what is rendered on the page, without having to write an entirely new view.  Right now the view will only render two lines of text.  We are going to expand on this in order to show some dynamic content in the browser.

Rendering with EJS

    With EJS, JavaScript between <% %> is executed, and JavaScript between <%= %> adds HTML to the result.  Lets give this a try.  First, in our Express file, index.js, we will send a list of items we want show on the web page.  Then, we will use EJS to iterate through this list and display the contents.

index.js

    We simply add a new property to the object we are sending to the render function.  The property items is an array containing three strings.  Now we will print these strings in our EJS file.

index.ejs

    We create a for loop that will iterate through the array we passed from our Express function.  The loop is places inside <% %> tags because we do not want the for loop itself to be added to the web page.  Inside the loop, we have a <li> tag that will place an item on the web page for each item in the array.  To display the item from the array, use the tag <%= items[i] %>.  This will look up the element in the items, array, and add it to the web page.  As you can see, these tags can be place anywhere inside normal html.  To view these changes, just restart the server and reload the page in your browser.  You should see something like this:

Express

  • red
  • green
  • blue

If you view the source for the page in your browser, you might be wondering why you don’t see any of the EJS tags that are in the view file.  That is because Express will evaluate the EJS tags before the page is shown, and only the results will be displayed.  EJS gives you flexibility when creating views for you website.  You will be able to use powerful embedded JavaScript to render views for different situations.

Node.js – A JavaScript Developer’s Dream

Node.js – A JavaScript Developer’s Dream

Here at Shockoe we are happiest when working with JavaScript. There are plenty of projects that call for other languages, like Objective-C, Java, or PHP, but the goal is to work with JavaScript whenever possible. For a decade I thought of JavaScript as this insecure toy language used to do miscellaneous effects on the web. I gave JavaScript another look when AJAX came into the vogue, but again dismissed it as a toy language with no real use. Then I started working at Shockoe, where I was very surprised to learn that JavaScript could be used for writing mobile applications.

Despite working for a company that primarily deals with mobile applications, I consider myself a web developer. I’ve been using PHP for a very long time and mostly just tolerated its inconsistencies and occasional strange syntax. PHP was just the way you did server side code for the web. Then I discovered Node.js. Now the goal is to write everything in JavaScript.

Node.js is advertised as being “for easily building fast, scalable network applications.” By default, Node.js performs very little I/O so blocking is not a concern. There’s an absurd amount of Node.js modules available from Node Package Manager (npm) that allow you to connect to almost anything imaginable. Most, if not all, modules for connecting to I/O provide async methods so that blocking remains of little to no concern.

To get started with Node, head on over to nodejs.org There are builds available for Windows, OSX, and Linux. Then head over to npmjs.com to see what modules Node Package Manager has to offer. There’s web frameworks, build harnesses, database drivers, and much more. Any developer who loves JavaScript owes it to themselves to explore the world of Node.js.

I’m at the point where I use Node.js for anything from giant web projects to minor fun tasks. At Shockoe we have taken an initiative to improve our health. One concern is that we spend all day looking at monitors which puts a lot of strain on our eyes. To combat this we have implemented a system known as the twenty twenty twenty rule. Every twenty minutes we take a twenty second break while looking at something twenty feet away. To alert everyone of the time we have a node server, running on our continuous integration machine in the corner, that turns a hue light purple for twenty seconds every twenty minutes. It’s enough to catch everyone’s attention without being extremely interrupting. This task could have been accomplished with cron, but I don’t want to schedule cron jobs. The goal is to write JavaScript.

In the upcoming weeks we at Shockoe will be expanding upon this post and, step by step, creating a project using Node.js.

Building a better Titanium app with Backbone Events

Building a better Titanium app with Backbone Events

Building an app with Titanium gives you access to all of the speed of a native framework while giving you the flexibility that you know and love from Javascript, but exposes you to all manner of potential memory issues that traditional native developers are not familiar with. Enter Backbone.js, a not-so-well-kept secret to creating a well structured app dizzyingly quickly. Backbone allows you to define events on most any javascript object, giving you flexibility and control over how your components interact with each other.

Dependencies and upgrading

If your project is built with Alloy, good news!  An older version of Backbone ships with Alloy by default, as well as its underscore dependency.  If you’re maintaining a classic Titanium project, you can download the most recent version of Backbone and underscore from here and use them like normal commonjs libraries.  Additionally, we have provided an updated version of Backbone that has been modified to work with the current version of Alloy.  To use it in an Alloy project, just place the minified version in your lib folder and add

to alloy.js.

An aside on the topic of mixins

Backbone is an example of an awesome design pattern that Javascript encourages, namely mixins.  The way mixins work is that they define a set of functions that can work if assigned to any Javascript Object.  This allows you to eschew classical inheritance structures in favor of defining small, self-contained pieces of functionality that can be harmoniously applied to a single Object (which can have a prototype, other mixins, or both!).  They’re also a great way to achieve an effect similar to classical inheritance in cases where you can’t use normal prototype chains, like Alloy controllers.  Mixins can be defined in a number of ways, be it by creating a normal Javascript object containing a set of functions that can be copied to another object, or by declaring a function that applies all of the functions in the mixin to a parameter object.  Backbone.Events is an example of a mixin declared as a normal Javascript object.

On to the main Backbone.Event

The core advantage of building a Titanium app with Backbone is its powerful event system, and it couldn’t be easier to use.  To mix in Backbone Events to an alloy controller, just add

to the beginning of your controller (note that you can substitute any javascript object for the first argument).

Now that you have backbone events mixed in to your controller, you can start listing to and triggering them.  First, let’s set up an event listener.

To break down that code snippet, using the ‘on’ function from underscore you can subscribe a function to be executed every time that some event is fired.  Then, from whithin the other controller, you can use the ‘trigger’ function to notify listeners of some action.  For example, if you had some picker controller, you could trigger a ‘change’ event whenever the user makes a new selection, and then listen for that event from the parent controller.

So why not normal callbacks?

The advantage of using Backbone events over just using normal Javascript callbacks is twofold.  For one, you can easily register multiple event listeners to a single event.  Since the event is just a simple ‘broadcast’, you can hook up multiple listeners for the same event without the triggering controller having to have any awareness of its listeners.  For example, you could set up a UI controller to listen to cache update events. You could then set up your network library to just broadcast update events.  Then, if you later need to hook something in to automatically update on cache update, you can easily listen to the same event.

Secondly, Backbone exposes a handful of functions that makes it very easy to clean up event listeners en masse.  You can use ‘off’ to dismiss event listeners individually, dismiss listeners for an individual event, or tear down every event listener associated with a given object.

In addition to this system for managing events, the most recent version of Backbone provides a number of functions to allow objects to better manage their event listeners.

The advantage of using the listenTo pattern is that either object can tear down an event listener shared by them. This has important implications for Alloy controllers: as long as you manage most of your cross-controller interactions through Backbone.Events, you can tear down every event listener originating from a controller with a single call. We can use this feature to set up intelligent disposal functions that let us tear down most references to a controller quickly and prevent memory issues.

And that’s it. From here, you can set up other controllers to listen to the dispose event and do things like remove the controller when its disposed or build out new UI on controller disposal. Then, after all of the dispose listeners have been handled, all event relationships are automatically disposed of. Assuming you clean up all of your references in dispose events, there’s nothing else you need to do for the average controller to keep memory in check. Bear in mind that things like app-wide events (such as events on Titanium.App, Titanium.Geolocation, Titanium.Gesture, etc.) can still lead to memory leaks and should be handled in your disposal listeners.

You can read more about Backbone.js at the project’s website.
For more information about Backbone’s dependency Underscore and how you can use it to code better and faster, check out our blog post!

Underscore.js – Everything you didn’t know you needed

Underscore.js – Everything you didn’t know you needed

Underscore.js (_.js for short) is a phenomenal javascript library that most web and Titanium developers are likely familiar with at this point.  What you may not know is that _.js is bundled with Alloy, letting you use the awesome collection of commonly used functions with little effort on your part.  I’ve compiled a few of my favorites here:

_.each

Underscore’s each function is a great alternate to Javascript’s built in for function, with the key difference that it allows you to have a local scope to work in (as opposed to Javascript’s built in for, which inherits the parent scope).

_.memoize

Memoize does exactly what the name says!  It takes a function, and returns a version of it that will only calculate its return value once for a given set of inputs, and then cache this value and return it on subsequent calls.  It’s absolutely great for functions that always give the same result but can take a long time to compute (the Fibonacci sequence is an oft-used example).  For more information, Wikipedia has a great page on memoization.

Another great use would be for hash functions (e.g. the also-bundled-with-alloy sha1)

_.isWhatever

Underscore provides a awesome set of isSomething functions that can tell you all kinds of things about a given variable, ranging from its type to whether it is finite. Examples include isEmpty, isArguments, and isDate.

_.once, _.throttle, and other function modifiers

_.once and _.throttle are great for controlling frequency of execution of functions. Simply put, _.once makes it so a function can only be executed once, and _.throttle rate limits a function so that it can only be executed once every so often (e.g. at most once every 200 ms).  Both are extraordinarily useful in the context of Titanium for dealing with issues associated with events getting created too quickly to be handled in a sensical fashion, such as a user tapping a button too quickly or scrolling too fast. Other awesome function processing functions include _.after (provided function is executed after being called a certain number of times), and _.debounce (function is only executed after it hasn’t been called for some period of time).

And more!

Underscore.js contains roughly 80 different commonly used functions for different purposes, too many for me to possibly go over here.  Take a look at their docs, and feel free to leave comments about your favorites below!