Andy Crouch - Code, Technology & Obfuscation ...

A Clean Fizzbuzz Solution

Water Splash

Photo: Unsplash

Fizzbuzz is an interesting little test based on a maths game used in some schools. Used to teach division, the Wikipedia entry states:

“Fizz buzz is a group word game for children to teach them about division.[1] Players take turns to count incrementally, replacing any number divisible by three with the word “fizz”, and any number divisible by five with the word “buzz”.”

Developers have used this game for many years to test interview candidates. It is also used for general programming and TDD practice (know as Kata’s). The profession has slightly altered the game and the version generally used is:

“Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.”

I have been using the Fizzbuzz problem as a Kata for one of my junior developers. They are very junior. Their training is focusing not only on language and framework features but also agile and clean approaches to coding. A lot of developers use Fizzbuzz to improve their TDD skills. Given this, I’ve always been quite surprised by the basic implementations found online.

My developer spent a couple of weeks creating slightly different versions. At each training session, we would discuss the approach taken and I would suggest changes. The developer was interested to see what my solution might look like. So I sat down and created what I consider to be an acceptable solution to the problem. This is very much a C# solution so please bear this in mind.

The full solution can be viewed on Github.

A lot of the solutions I see implement the logic in some fixed manner. For example:

public void DoFizzBuzz()
{
    for (int i = 1; i <= 100; i++)
    {
        bool fizz = i % 3 == 0;
        bool buzz = i % 5 == 0;
        if (fizz && buzz)
            Console.WriteLine ("FizzBuzz");
        else if (fizz)
            Console.WriteLine ("Fizz");
        else if (buzz)
            Console.WriteLine ("Buzz");
        else
            Console.WriteLine (i);
    }
}

It would be hard to test this code and no way to extend it without changing the implementation. If we had to change the logic for printing “Buzz” in place of numbers divisible by 4 this code would need to change. This is a clear violation of Bertrand Meyer’s Open/Closed principle. A clear explanation of the principle can be found here. To adhere to the principle I took a simple approach using an abstraction and reflection.

My FizzbuzzGenerator class was straightforward to write following a test first approach:

public class FizzbuzzGenerator
{
    List<INumberParser> _numberParsers;

    public List<string> GenerateResultsBetween(int rangeStart, int rangeEnd)
    {
        var resultSet = new List<string>();
        var inputRange = Enumerable.Range(rangeStart, rangeEnd).ToList();
        
        inputRange.ForEach(i =>
        {
            INumberParser numberParser 
                = Parsers.First(p => i % p.Divisor == 0);

            resultSet.Add(numberParser.Parse(i));
        });
        
        return resultSet;
    }
    
    private List<INumberParser> Parsers
    {
        get
        {
            if (_numberParsers != null)
                return _numberParsers;
        
            var interfaceType = typeof(INumberParser);
            return 
                _numberParsers 
                   = AppDomain.CurrentDomain.GetAssemblies()
                         .SelectMany(x => x.GetTypes())
                         .Where(x => interfaceType.IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)
                         .Select(x => Activator.CreateInstance(x))
                         .Cast<INumberParser>()
                         .OrderByDescending(p => p.Divisor)
                         .ToList();
        }
    }
}

I defined an INumberParser interface to outline the behaviour of any object that could parse an integer to a result string. This means that I have multiple INumberParser based objects to implement the Fizzbuzz rules. My generator class is then just used to find all of the instances of INumberParser and process each number in the range specified before adding the result of the rule to the resultSet list.

Each rule is implemented as follows:

public class BuzzNumberParser : INumberParser
{
    public int Divisor => 5;
    
    public string Parse(int number)
    {
        if (number % Divisor == 0)
            return "Buzz";
        
        return number.ToString();
    }
}

This is straight forward to read. We specify the Divisor that the rule will handle and provide a mechanism to parse an input number and return the result of the rule.

I do appreciate I could actually implement a base class that inherits INuberParser and reduce the parse code down to one instance but in this case I was trying to show agility of code to the developer.

The full solution can be found here.

The benefits of a solution along these lines is clear. Firstly, this code can be easily tested and was the result of using a Test First approach. Secondly, any extensions to the rules or changes of logic are restricted to each INumberParser based rule class. The Generator class never has to change. If I now need to handle a rule that prints “burp” for any number divisible by 50 then I define a new INumberParser based class and implement the logic. I build and run the program and it will work. A single place to update our logic. There are no messy if or switch statements.

The last thing I would say about this solution is that it didn’t take very long to create. Therefore, I would question a reasonable developer not being able to create a solution similar to this when given 20 minutes to code. If I ever used FizzBuzz as an interview question I would certainly rank a candidate higher for implementing a clean, agile solution like this as this is the approach we follow and the standard I’d expect within our codebase.

If you’d like to discuss any of my thoughts here then as always please contact me via twitter or email.

Onboarding New Developers

Man And Bike In Black And White

Photo: Unsplash

Over the past few weeks, we have had two new developers join the Open Energy Market team. It’s always enjoyable when new developers start. Two within a couple of weeks has meant some parallel discussions and observations.

I see it as vitally important how you onboard any employee to your company. How you welcome them on that first day sets a tone that can sometimes be hard to change later on. Remote developers are especially important. You want them to feel included and productive as soon as possible.

First things first. Once a developer accepts an offer I order a standard spec laptop and get it delivered to their home. A standard spec at Open Energy Market is quad-core, SSD and 32gb DDR4 ram. The developer can request a certain screen size but that is the base specification I insist they have. I also sign them up with a Bizspark licence and let them get on with getting their basic set up going.

By their first day, they have access to all the core applications and systems they need to do their job. This includes Slack, Dropbox and GSuite amongst others. It does not include hosted services such as AWS or Azure. If it requires training or explanation then we arrange that for within the first couple of days. Talking of Slack, always introduce any new member of the team on Slack and encourage everyone to say hi.

Once the introductions are over it’s time to get a development environment up and running. At present we have it well documented. Following the instructions step by step will see a developer up and running in a couple of hours.

For an employees first week I try to schedule time with the Management team. There is only the 4 of us but getting each of us to welcome the employee makes them feel as valued as they are. It helps build an understanding of everyone’s roles and how the company fits together.

From the second day, the developer has 2 main objectives. One, find a mechanism for learning the applications codebase. Two, put in place a change within the first 2-week sprint that we work to.

Point one, familiarising yourself with a new codebase is a personal thing. Different developers each have their own ways. Some like to have a range of issues to fix which provides broad exposure to the codebase. This is a good way to go. On occasion, I have found that due to a lack of context, the developers make incorrect assumptions and changes. Another approach which we tend to make all new developers do is to answer a questionnaire. The questionnaire is specific to us and was suggested by our very first developer when they joined. It has a range of questions relating to security, frameworks, logic, libraries amongst other things. This works really well. On average I find that besides fixing a small issue or making a small improvement it doesn’t take more than 7 days for the developers to complete it. When they have we go through their answers and fill in any immediate gaps.

Point two, getting the developer to make a visible change within the first sprint makes them feel like they immediately add value to the team. There is nothing worse ( I know) than spending 3 months learning a codebase and starting to make changes before anyone benefits from my work. I want the developers to be committing valid changes as soon as they are comfortable to.

I’d be interested to discuss how you onbaord developers via twitter or email.

Turning Off Notifications

Woman Whispering

Photo: Kristina Flour - Unsplash

Notification overload, no more.

I have disabled all of the notifications on my phone. In fact, the only time it now makes a noise is when a phone number I know about calls. That’s right, if your number is not in my phone then I will call you back when I am ready.

Why? That is easy. I got to a point where my phone never stopped notifying me of things. Calendar reminders, social media alerts, family SMS messages and Slack. When I am zoned in on a problem or am in the middle of a document I don’t need distracting. I stay in contact with my team via Slack. I have configured the notifications on Windows to appear top right-hand corner so as I work I can glance at them. I can decide on the fly if I need to answer there and then or if they can wait.

This is actually true of my phone. I use MightyText to track SMS notifications which appear top right of my screen. My phone sits facing me on the left. If a call comes from someone I do not know then the screen lights up and I can decide to answer it or not. On Android, if it is an unknown number but Google knows where the number originates then it shows me. All of this with no sound.

This has had a massive improvement on my concentration. For me at least, visual notifications which I can glance at and make a split second decision over have little impact. I must save 5 minutes a day from not having to switch my phone to silent before calls and meetings.

I’d be interested to find out other peoples thoughts on this via twitter or email.

Know your code

Man Looking At iWatch

Photo: Unsplash

“We learn from failure, not from success!” - Bram Stoker.

Or

From a long career, lots of lessons have been learnt which are worth sharing.

One lesson that I try to share with developers is that you have to understand how your code works. That is you need to know how it will work within the execution environment. If your code runs in the terminal it will work in a different manner than if it runs on a web server. Distributed applications need extra consideration and knowledge to ensure expected execution. Different framework versions even handle similar things in a different way. This is something that is lacking in a world of Google and StackOverflow. People paste code without fully understanding what they are adding to their code base.

Control Copy Paste Keyboard

Recently, a developer was trying to pass data to a class via the AppSettings mechanism. This is a NameValueCollection used to store Application Settings for the application. The code base had an abstraction for the Application Settings. The developer wanted to add one key-value pair to the AppSettings collection. This was to be able to use the data in a service class which he thought didn’t have access to the Session data. Now it is clear that this is not a clean solution. The thing that struck me was more that the developer didn’t realise that the code could never work. This code was to be in run in a load balanced, web application environment with a shared session state provider.

The values that the developer was adding to the AppSettings came from the Session. Each time the Session value changed it would write the value to the AppSettings collection. This is where it was going wrong. While writing the code it functioned fine. They would use single test accounts and the value would update as expected and the service class worked as required.

Then the developer assigned me a Pull Request to me for review. The first thing that I decided, having read the code, was to test the code with multiple Sessions. If you have code that is mapping Session data to an application state collection then it seems logical to test the code with many users. Three browsers and three test users later I had proved what I already knew and proved that the code would not work for many users. The first user’s data gets added to the collection and all is well. Then the second user’s data overwrites the first user’s data in the Application Settings during use. The service class attempts to access the data for the first user and instead gets the data added for the second user. Oh dear.

In talking to the developer they admitted that they had tested with one browser and one user. They also admitted to not fully understanding how the AppSettings code worked within the lifetime of a request. Ironically, the solution was to use the ASP.Net Session library as there was already a reference in the Service library.

It may seem a waste of time to let the developer get to a Pull Request without intervening. I disagree and think that within reason, allowing a developer to make a mistake and learn from it has enormous benefit. In this case, they learnt a lot about the configuration mechanism and load balanced environments. They also learnt to fully understand the implications of their code before pushing it for review.

Remote Working For Employers

Man Looking At Whiteboard

Photo: Unsplash

In my post last week, I covered my experience of working as a remote employee for over 10 years. This week I want to share my experience of building a fully remote team at Open Energy Market. I will share what I have found works, what does not work and things to look out for.

It is always exciting when you grow a company to the point where you can hire more employees. As an organisation, you can choose to limit your search to a radius of your office. You can choose to pay an expected salary band for within that radius. You can finally choose the recruiters that you will work with based on your location. All in all a fairly limited set of choices. Instead, you could opt to increase your radius to the whole of the UK. You could go wild and go global!

Why?

Well, the odds of you finding the perfect employee for your role within a limited radius of your office is slim. This is especially true of creative employees such as developers and designers. The very success of your company and product is reliant on the fantastic team that build it. If you’re based in a town dense with technical employees such as Silicon Valley, great! If not then look for what an employee can bring to your company and not where they live.

This leads me to hire for team fit. We have all worked with people who are at the very best of their game but who are a pain to work with. The developer who can write elegant code but is not able to work with others due to attitude. An excellent tester who’s approach to reporting issues borders on mimicry. When you get to build a team you should be looking for a good cultural and team fit. The employees should be fully invested in the company idea and the product. They should want to work for you no matter what instead of it being a local role. If you have a team then having the ability to hire like-minded people with a diverse skill set will be beneficial. If this is the first hire then hire someone with the skills you need that you would want to work with. Setting the team culture is much easier at the start.

The last reason you should consider a remote employee or team is cost. This point is very startup-specific. I am not going to shy from the fact that I can hire better people within the budget I have with remote roles. In hiring the first developer at Open Energy Market we found a developer through Hacker News. He had specific experience of early stage startups. He had recently been through Y Combinator with his previous startup. He was a very experienced developer that I hired on his requested salary. For me, I gained a senior developer for a mid-level developers salary. We benefited from looking beyond a 10-mile radius of our office.

So we have addressed the why now the how. I generally always advertise roles on Hacker News Who Is Hiring posts. Created on the first of each month, these posts allow anyone to advertise their roles. The posts are visible to millions of readers. I have had great success hiring from Hacker News. I have also met and interviewed some amazing people from around the world. In support, I generally advertise on one of the generic remote working job boards. We Work Remotely and Remote OK have had mixed results as have adverts on generic IT job sites. I have not yet used some of the newer developer community job boards such as StackOverflow or DZone jobs.

Interviewing should be a multipart process. I tend to hold a brief 30-minute call with all reasonable looking candidates that we shortlist. This is very useful for working out who wants the job because it is remote or because they see the challenge. Then I and my senior developer conduct a face to face interview. During that interview, we are looking for technical ability, team fit and skill fit. We get the candidates to either live code a generic problem or present and explain some of their own code. Almost all of these interviews are performed using Hangouts. If the candidate is going to join us in a remote capacity then let’s see how they go on video.

This brings us to having actual remote employees. If the above steps have worked you should end up with someone that slots straight in. The important part now is the tools you provide the team to communicate and collaborate. Team communication is vital. I have used a lot of whats been on the market over the last 10 years or so. I actually delay selecting the communications tool as long as possible so it can be agreed on by the team. At Open Energy Market, we use Slack. Slack seems to have a love it or hate it standing in the world but for us, it does what we need with no friction. We have integrations to email, Bitbucket, Jira and Confluence. This means that as we’re working the team is aware of what is happening as it happens. We have even integrated Slack into our own application to notify the team of everything. From new user signups to traded contracts, the team get notified via Slack. Finally, all meetings are conducted in Hangouts. It’s not the best tool but we’re used to it and it just works.

Bitbucket, Jira and Confluence are services hosted by Atlassian. They cover the core items needed to run a development team in my view. Bitbucket provides Git source control. It makes it easy to integrate with third-party applications allowing us to use it to automate our deployments. It also makes it very simple to set up rules and workflows for Code Reviews. Jira is a work item tracking application with a number of workflow methodology built in. We have used the Kanban workflow for the last few years to great success. Confluence we use to document everything from meeting notes to release logs. Both Jira and Confluence are very configurable.

This brings us to the final piece relating to remote employees, people! Once you have a remote team you need to ensure that you do not micromanage it while ensuring you stay connected. I make a point of not arranging needless meetings but it is good to get the team together once a week. I have found replacing the standard Scrum standup with a virtual stand up using Slack works well for us. This means we have a team meeting in a Monday, first thing and then each of us updates the team each day before 9:30 via Slack. The only other meeting that is mandatory for the team is a company-wide meeting on a Monday lunchtime. Done via Hangouts, each team, in turn, updates the rest of the company on what it has been doing. The final recommendation I have is to have 3 monthly reviews with each of your team. Take the time to chew over the last 3 months and see whats working and what is not. Set targets and write it down so you work to it.

My final advice is for when things look like they are not working out. Signs to look out for are lack of communication, inadvisability and a decrease in delivered work. Once this starts to happen long enough for you to notice, deal with it. Everyone has off days or days where they are so zoned into their task that they don’t communicate. Your role in running a remote team is to know your team so you know when this is the case.

If you’d like to discuss any of my thoughts here then as always please contact me via twitter or email.