Like most developers I’ve met, I’ve always believed consistency in code to be a good thing.

Recently though I’ve been starting to question if consistency is always a good thing.

What do I mean by consistency?

Consistency can be applied to many areas within a codebase. You can have consistent naming strategies, formatting rules, and code design patterns to name just a few.

When it comes to formatting, people can often have very strongly held views. Tabs Vs spaces, do braces for a function start with a new line, should you end a line with a semicolon, and so on.

If you are spending time thinking about formatting consistencies you are a very lucky developer. If those are your biggest issues, you’ve done a great job, go ahead and take the rest of the day off. Unless these formatting inconsistencies are stopping the code from compiling or causing massive readability issues, I wouldn’t really worry about them. Or better yet, have the conversation once and stick a linter in your project.

The other main area I’ve seen discussed when it comes to consistency is the patterns within the application logic. For example, how the data access objects are structured or how a request is parsed into the application domain.

Good points for consistency

Now don’t get me wrong, consistency can be very helpful.

One of the main aims I hear for consistency is making it easier for other developers to understand how the code works across the application. This is a strong point for consistency. It’s rare a single developer will be working on an application, so making things easy for your teammates is pretty important.

“Indeed, the ratio of time spent reading versus writing is well over 10 to 1. We are constantly reading old code as part of the effort to write new code. …[Therefore,] making it easy to read makes it easier to write” (Robert c Martin, Clean Code)

Keeping a codebase readable should be one of the main aims of a developer. One of the worst things a developer can do is to reduce the readability of code. By giving patterns to recognise, code readability can be another benefit of sticking to consistent patterns.

Bad points for consistency

It’s clear that consistency can be very helpful, but recently I’ve been thinking it might be a bit of a code smell. So rather than just sticking with consistency for consistency’s sake, maybe think about some of the following points as well.

Inertia

I’ve seen consistency become a real blocker when it comes to refactoring. When you have the same pattern in many places throughout a codebase, when you see a refactoring you want to implement, having to do that refactoring in many places can be time consuming. Sometimes to the point where the benefits of the refactoring are outweighed by the time to implement it.

Communication can help here. Maybe you don’t need to refactor every single instance of a pattern. Try refactoring the one instance you originally wanted to, but make sure you communicate with the team that you have done this.

Big refactorings scare me. It’s too easy for them to turn in to a thread that just won’t stop unraveling. I think the boy scout role is much more effective. Every time you touch code, leave it in a better state than you found it. Even if that’s just renaming one variable, the codebase will quickly start to look great. But I find the need for consistency at odds with this approach. It’s easy to feel, “I can’t just update this, it won’t be consistent with the rest of the application”. This can lead to just keeping the status quo.

The inertia of trying to make big changes is much greater than if you are making many small ones.

Highlighting duplication

If the consistency you are trying to protect is something like a design pattern, then maybe this is a sign of duplication of logic. The fact that there are multiple things done in a consistent way may mean there is a possibility for a cleaner more general implementation that you could be using.

Unit testing

If your unit tests are a mirror of your code then consistency can mean you have to update all your tests every time you refactor your code. However, your tests shouldn’t be a mirror of your code. The test suite should be a collection of the units of work. If you have to update all your tests every time you refactor, these are likely to be implementation tests rather than unit tests.

Making it easier for others

I’ve seen “making it easier for new team members to navigate around the codebase” be a reason why consistency is important. However, if consistency is the enabling factor for navigation, perhaps that is a signal that the code could be cleaner anyway.

By following Uncle Bob’s techniques for clean code, such as naming things clearly and many small functions that do one thing, the code could be easier to navigate. I would rather find my way around a code base that “reads like well written prose” (Grady Booch) rather than relying on spotting a duplicated pattern.

Conclusion

I’m not saying consistency is a bad thing or that it should be avoided. But if you are ever tempted not to refactor code to preserve consistency, I would be on the lookout for other code smells such as duplication, code that could be cleaner, or unit tests that are too closely coupled to the implementation.

I was looking for a spell check extension for VS Code to make writing this blog easier. After finding Code Spell Checker, I recommend it as a must have extension.

Once a spelling mistake is identified, you get the classic green squiggle, then Ctrl + . will bring up the spelling suggestions menu.

Expo device testing
Spell checking in VS Code!

The extension has made writing in VS Code an awful lot easier. I didn’t look for a spell checker to make coding easier, but it has had that bonus side effect.

I’ve never really thought about spelling mistakes in code before. Obviously if I spot a spelling mistake I’ll fix it, but I’ve never really thought about the impact on speed of development. However, recently I’ve been doing a lot more work with Javascript. A couple of times already, Code Spell Checker has caught a misspelled variable name. Code Spell Checker will even catch spelling mistakes in camel cased names. With JS being dynamic, these spelling mistakes would have only been caught at run time and I would have had to track down the bug.

I’ve been building a React app recently that uses AWS Cognito for its authentication. Several of the components were using the same Auth logic to check if they should render or not.

To remove the duplication and keep my authentication logic in one place I created a Higher Order Component.

Signing in with AWS Cognito Javascript SDK

I wanted certain pages of my React application to be only reachable by authenticated users. For authentication I’m using Cognito from AWS along with the Amazon Cognito Identity SDK for JavaScript.

The AWS JS SDK makes it really easy to interact with Cognito from your JS application. Signing up users, verifying users’ emails, and signing in users are pretty straightforward but those are for blog posts for another day.

To check if a user is signed in, you create a user pool to get the current user. Then if there is a current user, get their current session.

var poolData = {
    UserPoolId: '', // your user pool id here
    ClientId: '' // your app client id here
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var cognitoUser = userPool.getCurrentUser();

if (cognitoUser != null) {
    cognitoUser.getSession((err, session) => {
        if (err) {
            console.log('error:', err.message || JSON.stringify(err));
            // redirect to sign in page
        }
        // handle authenticated user
    })
} else {
    // redirect to sign in page
}

This is pretty straightforward but you don’t want to be duplicating this code on every page that you want to check if a user is authentication on though. This is where Higher Order Components for React can help out.

Cross cutting concerns

Application requirements that are needed throughout an application but aren’t necessarily part of the main application are sometimes referred to as cross cutting concerns. Logging and security are good examples of cross cutting concerns.

Using the decorator pattern is a good way of dealing with cross cutting concerns. This allows you to keep your actual application logic clean while adding, potentially multiple, decorating pieces of functionality around it.

Higher Order Components

A Higher Order Component is like a higher order function in Javascript. It is a function that takes a component and returns a new component.

Acting just like the decorator pattern, a Higher Order Component can be used to add logic or cross cutting concerns to components while keeping the original component clean.

Creating a Higher Order Component

For my needs, a Higher Order Component will allow me to add my Cognito authentication logic to multiple page components cleanly. In the example below, the Cognito user check is in the componentDidMount function. If the user and session is valid, a boolean check in the state of the component is set to true. If the user check or the session doesn’t return successfully the component will redirect to the sign in page.

In the render function, it checks the loggedIn boolean in the state, then if true, it returns the component that was passed to the Higher Order Component.

import * as React from 'react'
import * as AmazonCognitoIdentity from 'amazon-cognito-identity-js'
import { withRouter } from 'react-router-dom'

const withAuth = Component => {
    class WithAuthUser extends React.Component {
        constructor(props) {
            super(props);

            this.state = {
                loggedIn: false,
            }

            this.onSession = this.onSession.bind(this)
        }

        onSession(err, session) {
            if (err) {
                console.log('error:', err.message || JSON.stringify(err));
                this.props.history.push('/signin')
            }
            this.setState({ loggedIn: true })
        }

        componentDidMount() {
            var poolData = {
                UserPoolId: '', // your user pool id here
                ClientId: '' // your app client id here
            };
            var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
            var cognitoUser = userPool.getCurrentUser();

            if (cognitoUser != null) {
                cognitoUser.getSession(this.onSession)
            } else {
                this.props.history.push('/signin')
            }
        }

        render() {
            if (this.state.loggedIn) {
                return (
                    <Component {...this.props} />
                );
            } else {
                return null
            }
        }
    }

    return withRouter(WithAuthUser)
}

export default withAuth

To use a Higher Order Component

To use a Higher Order Component you import the component like any other component;

import withAuth from './withAuth'

Then wrap it around the component you want to apply the decorating logic to;

const ExampleComponent = () => {
    <p>My component!</p>
}

export default withAuth(ExampleComponent)

For some more examples of Higher Order Components in React, you can check out the documentation for them here.

I think retros are great. I think the idea of reflecting on how the work is going and coming up with ideas for continuous improvement is awesome.

However, I find that running the same retro format every time can make retros lose their impact. They are at risk of the team just turning up and going through the motions.

What I hope to get out of a retro

My aim when I run a retro is to check in on how the team are feeling everything is progressing and to come out with an action to work on until the next retro. How many actions and what they look like is a topic for another day though.

The retro idea

I’m sure most people have come across the retro format of “stop, start, continue” or a theme close to it.

“Stop, start, continue” is an excellent format and I often run retros with this format. However, even with positive teams, I find a lot of people struggle to put anything in the continue column, and when they do they rarely vote to talk about those points.

I propose a retro format where the only category of talking points is “continue”. Hopefully this should force people to remember what went well since the last retro. Furthermore, if the positive points are the only talking points available, the discussion will have to be on them.

Extreme programming

I’ve been in a lot of retros where we capture positive points but when it comes to discussion time, some people believe “there is no point in taking about the positives”. I think this is wrong. Just because something is good, it doesn’t mean it can’t be even better. Or if it’s not nurtured, that positive may not happen again.

I really like the extreme programming idea of, if something is good, do more of it and take it to the extreme.

How to run it

Starting a retro with a check in activity can really help to make sure everyone is engaged with the meeting. A quick check in I like to run is, going around the room, everyone is to say how they felt about the last sprint in one word.

Then ask people to write down all the positive things since the last retro on post it notes. As many as they can in 10 minutes or so.

Once everyone ideas are down, ask people to stick them on the wall, while giving a very brief description of them. Getting people to group any tickets they have as they stick them up can be beneficial here.

To decide which points to talk about, dot voting can be very helpful. Each person gets three points to put on any tickets they want to talk about, all the on a single ticket of they prefer. Then the tickets with the most points is the topic of discussion.

It’s great to try and get some actions out of the discussion so the team is improving s little bit each retro. I’ll be covering how to capture and track to actions in another post.

Be positive

Hopefully by mixing up your retro formats it’ll help keep the team engaged and get the creative juices flowing to help come up with great actions.

Also, if the team is going through a bit of a tough patch, by focusing on the positives, it might help to avoid the retro from becoming a bit a moaning session.

Tired of opening multiple terminals to run processes? Then you should check out concurrently on npm!

What was my issue?

Recently I’ve been working a lot more with JavaScript. This has been great, I’m finding the js world a lot more mature recently.

I’m loving the tooling around JS. Particularly tools such as Parcel JS and good old Express.

However running multiple terminals for different processes was causing me a headache. When writing with others on a project, having to know multiple commands to run the development environment also creates a cognitive overhead that shouldn’t be there.

What is concurrently?

Concurrently to the rescue!

Concurrently is an npm package that allows you to run multiple commands concurrently. A very well named package this one.

How I used it

I’m never really a fan of installing packages globally, and I wanted to use concurrently via npm scripts so I installed it as a dev dependency.

npm install concurrently --save-dev

Then with the concurrently command you can pass multiple other commands at the same time, remembering to surround commands with quotes.

concurrently "my process" "my other process"

To add as a npm script, remember to escape the quotes

"start": "concurrently \"my process\" \"my other process\""

Other features

You can find the full documentation here

There are loads of options that look useful such as killing other processes of one dies and changing how the prefixing works.

However, since my original issue was to simplify starting a dev environment when working with others remotely, using wildcards to list commands to run looks great.

For example;

concurrently "npm:watch-*"

Anything that can speed up my development time is good by me, so go give concurrently a try.