Softwire Blog


Advanced Clean Code


15 March 2017, by

This post is a quick overview of patterns I have picked up over the years that I aim to use when coding and usually end up pointing out in code reviews.

These aren’t hard and fast rules, but to me, this post forms an extension to Uncle Bob’s clean code (which you should read right now if you haven’t already!).

(more…)

A quick guide to javascript streams


16 January 2017, by

In this short article, I’ll lead you through a crash course on what a stream is, and how you can harness them to make your code more understandable.

If you want to try out any of the examples here, they will work with the excellent library bacon.js.

So what is a stream?

A stream is a sequence of objects, but unlike other sequences, it’s handled lazily (so the items aren’t retrieved until they’re required). This means that unlike a normal List, it doesn’t have to be finitely long.

You can put anything in your stream characters, numbers or even user events (like keystrokes or mouse presses). Once you’ve got your sequence, you can manipulate it in lots of different ways.

Streams can also completely remove the requirement to think about time, meaning fewer race conditions and therefore more declarative code. This removal of the need to represent time in code also results in architecture diagrams which are easy to draw and reason about.

Manipulating your stream

Now that we know the purpose of a stream, how do we manipulate it? What follows is a selection of functions that can be called on streams along with visual representations of the effect of these functions when called. It should provide everything needed to set up and use some programs which utilise streams.

map(f)

Map takes a function f. Then, for every item that appears in the stream, it applies the function f to it and produces a new stream with the new values.

scan(f)

Scan takes a function f. Then for each value in the stream, applies the function to the previous result along with the current value. This is similar to fold, but the output is a stream of all the values rather than just the final value, which fold would provide.

filter(f)

Filter takes a function f, then for each value computes the function, and if it evaluates to true, puts the value into the output stream, else discards the value.

merge

There are several ways to combine two streams. Using merge will take values from both streams and output values (in the order they are received) into the output stream.

This differs from concat, which takes two streams and returns all of the first stream before returning all of the second stream.

sampledBy(f)

SampledBy takes a function f and two streams (A and B). The function f is then called whenever a value is provided by stream A, passing in the last value from each stream. In the example below, a value is created in the output stream whenever a value occurs in the top stream. The output is then created from the value in the bottom stream.

slidingWindow(n)

SlidingWindow takes an integer n and returns the last n values from the stream as an array each time a new value occurs in the input stream.

Stream Summary

So in summary, you can use stream functions to manipulate streams in a multitude of different ways. You should use streams to remove the time component from code, allowing for simpler to understand and debug code.

This post first appeared on Chris Arnott’s blog.

Focus on the future, not the present


6 December 2016, by

What follows are three examples of how focusing on the future improves efficiency over focusing on the present.

Running — don’t look down

I often like to run at the weekend. I’m not sure what I’m running from, but I feel significantly more happy for the rest of the weekend if I go for a run on Saturday morning.

I’ve got some tactics to make sure I actually go for my run, as I’m very good at putting it off. Giving myself some accountability and telling my fiancée the night before helps, as she then keeps reminding me until I go out. I also find removing barriers to starting very helpful, by which I mean make sure everything is ready for me to head out the night before. This usually involves putting my running shoes by the door, and sleeping in my running shorts.

I’m not running with any particular aim at the moment, other than my happiness and fitness (although given the advice I’m giving in this blog post, perhaps I should have a more tangible goal to be aiming for), but I do use run keeper to track my run. This keeps me focused on my pace and encourages me to try my hardest. This also means I can notice when I’m speeding up/slowing down, to try and keep a consistent pace.

The main factors that I find, which affect my run are:

  • hills
  • posture
  • focus

Hills are obvious. If it’s steep, I’m slower. Posture is perhaps less obvious, and I’m not going to focus on it here, but good posture aids breathing, and consequently speed.

Focus is the big thing here. I’m much faster if, rather than staring at my feet, I focus on where I’m running to. Unfortunately, the more exhausted I am, the more difficult this is, so I’m active in checking where I’m looking while I run. If I find my head drooping, and my vision staring at the floor, I revert it back to far away, and focus on getting myself there. This helps me reach that place, and means I get to pay more attention to my surroundings as I pass them by.

Projects — where is the project going?

I’ve spoken about this before in Don’t touch the patient, but I was mainly talking about tech leads in that post. This point applies more generally to everyone on a team.

You need to know where your project is heading, or your short term decisions will be in the wrong direction.

If you only focus on your current tasks, it’s easy to not spot things that will be an issue a week/month down the line. It’s important to spot these issues and resolve them early, as they are easiest to fix the earlier you address them.

To maintain this forward looking vision, it is important to know how your current tasks fit into the larger picture. What is the higher purpose of your work, and what can you do in the present to ensure that your work fits in with everything else going on. Working this out will involve communicating with other people to know what their aims are. Often other people will come to you first, but if they don’t, ensure you know who to talk to and make sure that the conversations are happening.

Work — where am I going?

At the highest level, this focus on the future applies to your whole career. If you only ever focus on what you are doing this day/week/month, then when you come to reflect on the past year, you’ll find that you missed the chance to take the opportunities provided to you to further your career and drive it in the direction that you wanted.

Zoe Cunningham has written an excellent series of blog posts about getting the career you want, which I would recommend to anyone who wants to know more:

What do you want

Make a plan

Do it

Summary

There are lots of situations in everything you do to ensure your focus is in the right place. Your life will be easier overall if you make sure that you focus on the future, as it will allow your present tasks to be progress you to your goals. Without this anticipation, you may find that you have not ended up where you expected, with lots of work required to get back on track.

This post first appeared on Chris Arnott’s blog.

Using sqlite for dev nodeJS environments


29 November 2016, by

This post will explain how to get one click DBs working in nodeJS.

Problems with your zero to hero

I was recently working on a NodeJS project, and it was set up to use a mySQL database. This was fine for production, but meant that people joining the project had several manual steps to get the project working.

  • Install SQL server
  • Set up a SQL database
  • Update the NodeJS config to point to the database.

This isn’t too difficult to do. But I wanted to reduce the ramp up to getting the project up and running on a dev machine.

This meant moving to a database that could configure itself from whatever was checked into the codebase.

One option would have been to translate the steps above into code so that running a command would create a SQL database that was configured to be used by the code.

This would have been overkill, as there are much better options.

I chose to instead configure dev and test environments to use a local sqlite database.

Local sqlite database

A sqlite database can be added as an npm dependency, so that it is installed as part of dependency management when a new developer checks out the code.

"dependencies": {
  "sqlite3": "3.1.4"
}

Now that sqlite has been added as a dependency, it can be called from the ORM that we’re using. In this example, I’ve used Sequelize as the ORM, as once set up, it allows easy mapping of Javascript objects to database objects, as well as having built in support for database migrations.

The next thing to do is to have a configuration file which details how to connect to the database in different environments:

module.exports = {
  development: {
    dialect: 'sqlite',
    storage: 'data/dev-db.sqlite3'
  },
  test: {
    dialect: 'sqlite',
    storage: 'data/test-db.sqlite3'
  },
  production: {
    username: process.env.RDS_USERNAME,
    password: process.env.RDS_PASSWORD,
    database: 'ebdb',
    port: process.env.RDS_PORT,
    host: process.env.RDS_HOSTNAME,
    dialect: 'mysql'
  }
};

This config.js file shows that in dev and test mode, we’ll connect to the sqlite database which is stored in the file “data/<env>-db.sqlite3”.

In production, it instead connects to an RDS instance (the production machine in this project was running on AWS), with the connection details stored in the environment on the cloud machine (rather than being checked into the code).

Now we need to setup sequelize to use the correct database when it is initialised. This is done in the index.js file under the models folder:

var path = require('path');
var Sequelize = require('sequelize');
const basename = path.basename(module.filename);
const env = process.env.NODE_ENV || 'development';
const config = require(path.join(__dirname, '..', 'config', 'config.js'))[env];
const db = {};
var sequelize = new Sequelize(config.database, config.username, config.password, config);

This code fetches the relevant section of the config.js file, and uses it to initialise the ORM. What’s not shown above is the code that loads all the models into Sequelize. We’ll leave that as an excercise for the reader.

As you can see. This file is using an environment variable to determine what mode we are running the code in. All that’s required to run in production is set NODE_ENV in the environment variables to be equal to “production”.

The app can now be started using “npm start”, which will start, using the dev database.

Migrations

Just a quick note here on using Sequelize for database migrations. You can hook your migrations into the “npm start” command above by adding the following to your package.json file:

"scripts": {
    "prestart": "sequelize db:migrate -c config/config.js"
}

Summary

So what have we learnt?

  • You should try and ensure setting up a project is as easy as possible for new developers
  • You can use different environments variables to separate out dev/test/production environments (and default to test).
  • This method can work, even if you are deploying to the cloud.
  • You can easily add database migrations into the start command of your application.

This post originally appeared on Chris Arnott’s personal blog.

Cross platform phone apps


28 October 2016, by

If you want to write a phone app, and want it to run on multiple platforms, but don’t want to spend large amounts of time maintaining two code bases, then there are several solutions that allow writing one app, and deploying it to several platforms.

These multi-platform apps work by running a mini website on a phone, which is accessed via a web view, which is how the app appears native.

In this post, we’ll discuss several different approaches to writing a multi-platform app, and have a look which situations you should choose each option.

(more…)

Submitting your cordova app to the apple app store


12 October 2016, by

These days, everyone has an app. If you are one of the people who decided to write a cross platform app using cordova and would like to now post it to the app store, then keep reading and I’ll explain how to go about doing that.

Just a word upfront, in order to build your app, and to post the built app to the app store, you will need an apple machine.

Building your app

There are three steps required to build a release version of your app. Create a certificate, create an app identifier and create a provisioning profile. Once you have done these steps, you will be able to build a signed ipa of your app.

Create a certificate

First, you will need to login to Apple’s developer website. If you do not have an app id, you will need to create one, and you will also need to register as an Apple Developer, which will cost you $99.

Now that you are logged in, go to the distribution certificates page, and create a new certificate by clicking the plus button, marking your certificate as Production > “App Store and Ad Hoc”, and then following through the instructions on the website, which involve creating a signing request.

Create an app identifier

Again, the first step is to login to Apple’s developer website. This time, go to the app identifier page.  Fill in a short description, and then specify the app identifier for your app (this is stored in the config.xml in your cordova project:

<widget id="com.softwire.exampleApp" ... >

At this stage, if you want to add any extra services to your app (e.g. PushNotifications) then you will need to mark them on the app identifier.

Create a provisioning profile

As with the other steps, you need to login to Apple’s developer website. Head over to create a new Provision Profile. Select Distribution > “App Store” then continue.

On the next page, you will need to select the App ID that you have just created and click continue.

On the final page, you will need to select the certificate that you have just created and click continue.

Finally, give the provisioning profile a name, and click continue again.

You do not need to download the provisioning profile, we will get XCode to do that for us in the “Submitting your app”.

Submitting your app

In order to submit your app to the app store, you will need to build the signed ipa file, create an app store listing, and then finally submit the app you have built.

Building a signed IPA

Now that you have created a provisioning profile (see above if not), you must get xcode to download it. To do this, login to your Apple account on XCode (Preferences > Accounts), and then click the + button and follow the instructions to add your account.

Once your account has been added, select your account in the left panel, and click “View Details…” in the right panel. On the screen that opens, you should see the provisioning profiles attached to your account. One of these will be the Provisioning Profile you created above. Select the Provisioning Profile and click download. This will now be available to xcode when building your project.

The next step is to inform cordova of which provisioning profile to use when building. This is done using a build.json file. You should create a build.json file, and include in it the id of the provisioning profile that you downloaded.

Finally, you can now run a build on your mac using:

cordova build ios --device --release --buildConfig build.json

This will create a signed ipa of your app under

platforms/ios/build/device/*.ipa

Creating an app listing

Login to iTunes Connect. From here, you can go to the apps page, and then create a new project. You will now need to fill in details for your app (there are lots to fill in, but the help Apple provides is quite useful), and ensure that you have uploaded screenshots of the app running on both phone and tablet (if relevant).

Once you are happy with the details, save them.

Submitting the IPA to the app store

Now that an app listing has been created, the next step is to upload the build (created above) to Apple.

To perform this upload, you will need Application Loader 3.0. You can download this from the “Prepare for submission” page on the app listing.

Once you have Application Loader installed, login and click choose. Select the ipa that was built earlier, which will upload the app to Apple. It will automatically be linked to your app listing, as the app’s id will match the one specified on the app listing.

After upload, the ipa will be processed by Apple, and following that, can be selected as the version that should be published to the store. If you’re happy with everything, then submit the app to review.

Apple will now review your app, and it will appear in the app store when it is ready. The review process will take a couple of days, and you will receive an email when the submission is complete.

Writing Good Documentation


28 September 2016, by

There are certain standards that govern good design and user experience. But eventually we all need to do something out of the ordinary or sufficiently complex that it will be accompanied by documentation. I’m not talking about the comments you leave in code (that’s a whole other kettle of fish). I am discussing the big document you have to write, which explains the nuances of your API, and how best to use your shiny new touch gestures.

If you think it’s almost as boring writing these documents as it is reading them, then I say you’re doing it wrong!

If you read on, I’ll explain what you should be thinking about before writing any documentation, and how this will help you enjoy the writing process more, as well as ensuring the end user gets the most from documents you produce.

(more…)

Speed Coding 2016 – Q4 Solution


3 August 2016, by

This post explains the solutions to Question 4 of our speed coding 2016 competition. If you haven’t yet read the question, head back and have a go now.

(more…)

Speed Coding 2016 – Q3 Solution


27 July 2016, by

This post explains the solutions to Question 3 of our speed coding 2016 competition. If you haven’t yet read the question, head back and have a go now.

(more…)

Speed Coding 2016 – Q2 Solution


20 July 2016, by

This post explains the solutions to Question 2 of our speed coding 2016 competition. If you haven’t yet read the question, head back and have a go now.

(more…)