An Introduction to Checkstyle


Checkstyle is a tool that can be used by developers in order to help teams follow coding conventions on a Java project. I recently used this whilst developing a Battleships game in Java with a group of others as part of a university module (maybe a post for another day?..).

Why use Checkstyle?


Coding conventions and standards are a way to ensure that code is formatted consistently across a project, team or organisation. The benefits of using them are pretty well known and well documented but it essentially comes down to making the code more readable and accessible to yourself and other developers.

Checkstyle helps developers to follow a coding convention by pointing out errors or warnings within the IDE based on an XML configuration file that you provide in the project. The configuration file’s format is well documented, easy to read and easy to edit. On our project we chose to base our standards on Google’s guidelines (google_checks.xml) which we then adapted to suit our own coding style (checkstyle.xml). We also used Travis CI to build our project each time someone pushed new code and if compilation and tests passed then we would get a notification in our team’s Slack channel, similarly if anything went wrong we would get a notification to let us know we needed to fix something. As we were using Checkstyle with the Maven plugin this meant that if code was committed which didn’t comply with our standards then the build would fail1.

How to install & use Checkstyle


Installing and getting Checkstyle to work with Maven initially took a few attempts and gave quite the headache but I put that down to my lack of experience with Maven and in the end it was worth it. I’m hoping that by documenting the process here others will be able to save time by not having to follow my process of trial and error!

Maven

In the pom.xml put the following block of code into the <plugins> section.

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-checkstyle-plugin</artifactId>
	<version>2.17</version>
	<executions>
		<execution>
			<id>validate</id>
			<phase>validate</phase>
			<configuration>
				<encoding>UTF-8</encoding>
				<configLocation>checkstyle.xml</configLocation>
				<consoleOutput>true</consoleOutput>
				<failsOnError>true</failsOnError>
				<linkXRef>false</linkXRef>
			</configuration>
			<goals>
				<goal>check</goal>
			</goals>
		</execution>
	</executions>
	<dependencies>
		<dependency>
			<groupId>com.puppycrawl.tools</groupId>
			<artifactId>checkstyle</artifactId>
			<version>7.6</version>
		</dependency>
	</dependencies>
</plugin>

Note – the configLocation field can be removed and Checkstyle will use the default config (sun_checks.xml) but as mentioned earlier on our project we used a custom configuration and simply named it “checkstyle.xml” in the root of our project.
It’s also worth mentioning the dependencies section where we explicitly tell Maven to use version 7.6. Without this section Maven will use version 6.11.2. This was something I only solved recently but it prevented us from using some of the newer checks available during development.

After setting up the configuration file (or choosing to use the default) running ‘mvn validate’ in the command line should give you the following output.

...
[INFO] --- maven-checkstyle-plugin:2.17:check (validate) @ Battleships ---
...

Below that line you will see a list of errors or warnings if your code does not follow the defined convention.

That’s it, your project is now set up to run Checkstyle with Maven!

Eclipse

There is also an Eclipse Checkstyle Plugin available for Checkstyle which will allow Eclipse to display errors and warnings to the user in the ‘problems’ tab. This makes it easy for developers to see jump to the offending pieces of code and fix it to comply with the coding standards in the configuration file.

Checkstyle throwing a variety of errors in Eclipse.
Checkstyle throwing a variety of errors in Eclipse.

Happy Coding!


1 The severity of “non-compliance” could be configured to either throw a warning or an error based on which rule had been broken. For example a line length of greater than 100 may throw an error but an extra whitespace somewhere may just cause a warning.

 

An Introduction to MuleSoft Anypoint Studio

What is Anypoint Studio?


Anypoint studio is a tool for building integrations & APIs for systems. it is based on eclipse (the popular open source Java IDE) so provides a familiar environment for many. It is a graphical tool which has a low learning curve and makes it easy to build integrations. Connectors, as the name suggests, are the part in a “flow” which actually connects to a system and extract or import data. There are many built-in connectors such as Salesforce, databases, ftp and even Facebook & Twitter. It is also possible to download more that have been built by the community from the Anypoint Exchange or develop your own if what you need isn’t available. The following guide shows just how quick and easy it is to create a MuleSoft application which grabs data from a system and transforms it before sending it to a different system.

Creating a basic app – Salesforce to HTTP


Mule Anypoint – Salesforce Flow

The flow that we will create will return data from Salesforce (Accounts in our example) to the browser in JSON when visiting http://localhost:8081/salesforce.demo

  1. Create a new Mule project (File -> New -> Mule Project).
  2. In the right panel search for “HTTP” and drag the result across into the main area, do the same for “Salesforce”, a “DataMapper” and a “Logger” so it looks like the image above. We now have the basic outline of our flow so it’s time for some configuration.
  3. First click on the HTTP connector that we have put in the flow and click the plus next to connector configuration in the panel at the bottom. Enter “salesforcedemo” in the base path field and click ok. Note – If you are running something else on port 8081 then you will need to  change that setting to a different port.
  4. Create a (free) developer Salesforce account, add some Account records and then do the same as above with the Salesforce connector, choose basic authentication, enter your account credentials (you will need to request a security token in Salesforce and enter that) and test connection. Assuming it succeeded, hit okay twice and back in the bottom panel next to operation choose “Query” from the drop-down box and enter the following: SELECT Name,Phone,Type FROM Account.
  5. Next we need to look at the DataMapper which takes data in one format and converts it into a different format as it says on the tin. In our case we want to transform the Salesforce data we have received into a JSON format and output that to the browser. In the configuration for this component we have 2 parts – Input & Output. The input side should automatically detect the Salesforce object we are grabbing but we will need to configure the output. Next to Type choose JSON, select From Input -> Copy Structure. Then click Create Mapping.
  6. In the logger configuration simply enter #[‘Sending to browser’] in the Message field.

Finally run the application by right-clicking the project in the left hand side browser -> Run-As -> Mule Application. When you see the word DEPLOYED in your console that means your application should now be running and if you visit http://localhost:8081/salesforcedemo you should retrieve a JSON view of all the accounts in your Salesforce environment.

 

How to mass unfollow on Twitter!

Yesterday, I wanted to unfollow everyone on an old account on Twitter. When searching Google for a tool to do this for me I found the ones that existed either weren’t very good or wanted a fee to do it (the tools that required a fee had many other options and features such as only unfollowing people who aren’t following you). After trying a couple of the tools I still had not managed to unfollow all the users I was following so decided to try and find my own solution and here it is:

1) Login to Twitter and click Following.

2) Scroll down to the bottom until everyone your following has loaded (Tip: press the end button to get to the bottom quicker).

3) Open up your browser console (CTRL + SHIFT + J for Chrome).

4) Copy & Paste the following Javascript and hit enter:

var el= document.getElementsByClassName('button-text unfollow-text');
for(var i=0; i<el.length; i++){
    el[i].click();
}

5) Wait a second or two depending on how many users you are following.

Done!

Apps for Good

 

Today I spent my time reviewing and discussing mobile application ideas from 1000’s of school children, from 213 schools (and counting!) across the country. The scheme is called Apps for Good and is run with the intention of teaching 10-18 year olds problem solving, basic programming, and creativity among other skills through technology.

How does it work?


The schools involved are provided with the course content, training and connections with the “Expert volunteers”. From here the children will split up into groups and have to come up with an idea for a unique mobile application. From this idea they will make a video pitch , a slideshow describing the idea and wireframes showing how they intend the application will look and be navigated. The groups are then able to have a session with an “Expert” which consists of a video call over Skype where the idea can be screened, questions can be asked and feedback can be given.

The groups can then submit their app ideas to Apps for Good who will then begin to filter through the ideas narrowing them down from hundreds to just 6. The groups behind the six ideas are then invited to London to give a Dragons Den style pitch to judges. The winning idea will then be fully produced and made available on the app store!

Previous winning apps can be seen here.

How can you get involved?


There are many ways to get involved in Apps for Good, the most accessible way would be by becoming an Expert like myself. There are many different areas to pick from in terms of what your area of expertise are from technically feasibility to user experience. Once you have successfully signed up you will begin to receive session requests which is where you would spend an hour of your time on Skype talking to a group who would like some advice, and feedback on their ideas. If you are an employee or member of a corporate partner of Apps for Good you may get the chance to have a session of reviewing all the apps submitted.

The most valuable way of getting involved would be to spread the word and let as many people you know about the scheme including schools, organisations and people in the mobile/technology industry.

For more information on getting involved visit: Get Involved.


Overall, Apps for Good is a great programme for bringing better and more technology education into schools. I had a great time seeing the ideas that some of the groups had come up with and how enthusiastic and passionate they were about them!

Do what you want to do.

In September 2012 I began to study for a degree in Computer Science at the University of Manchester. By January time I found myself really not enjoying it there and wanting to leave. I did not have a back up plan and knew if I left I would be unemployed, deciding whether to leave or not was a big decision to make.

I had a brief look into the possibility of getting an IT job without a degree and thought it would be possible and I would be enjoying myself more than at the University. I knew if I stayed I would be there for another 3 years which I really didn’t like the thought of so made the decision to leave. I knew I wanted to get a job in IT, and after looking at job listings I decided to aim for a technical support role in IT (as opposed to software development) as there were many more roles available and generally less qualifications were required. At heart I am a software developer but decided to be realistic since my main goal was to get a job in IT (beggars can’t be choosers!) and began to study for IT exams (COMPTIA A+) to eventually get a job in a technical support role.

I am currently writing this on a train, paid for by the company I now work for. I have gained my dream job working for a major IT company as a software developer, gaining this job makes my decision to leave University, the biggest but best decision of my life.

Ultimately, we only get one chance to live and why waste it doing something you don’t enjoy.  We have to take chances sometimes to get what we want or need. This should obviously be taken with a pinch of salt, everyone  has to work and not everyday can be perfect but if you find everyday is a chore then maybe it is time to take a chance.

When I left University I knew I wanted to get a job in IT since it is what my passion is, and felt capable of getting a job. Luckily, I was able to make the decision to leave without pressure to stay (eg. Financially if it was a job).  If you are in a job you really don’t enjoy, maybe you could start studying during the hours you don’t work towards a job you are passionate about and think you would enjoy. It may be hard working essentially doing maybe twice as much work but as long as you put the work in it will pay off eventually.

I feel like the following speech by Steve Jobs sums it up the best.

 

The Monty Hall Problem (Part 2)

If you are unfamiliar with The Monty Hall Problem please read the first part of this blog post here.The monty hall problem program

Due to my interest in programming and interest in this problem I decided to bring the two together and created a program that replicates the situation and outputs the statistics of wins and losses with switches and without (where the results can be seen further down).

Computing the Problem

I have uploaded the source code to the program which can be found here.

The program works by creating 3 doors at the start of each game and randomly choosing 1 to be the winner. The program then asks the user to pick one of the doors either 1, 2 or 3, after this it will then display one of the other doors (if the user has picked the winning door it will randomly choose one of the other 2 doors to show). The user is then given the choice to switch the door if they want to. The program then tells the user if they won or lost and prints out all the statistics of the total games which can be viewed below.

To make it easier to quickly run the program multiple times I created short java program to produce a file that can then be fed into the standard input of the main file to run the game 1000’s of time quickly and view the results. That program can be found here.

The Results

I ran the program multiple times using the file printing program to give me a different number of inputs each time from 20 games to 20,000 here you can see the screenshots of the results below.

Results of 10 switches and 10 none switches.
Results of 10 switches and 10 none switches.
Results of 100 switches and 100 none switches.
Results of 100 switches and 100 none switches.
Results of 1,000 switches and 1,000 none switches.
Results of 1,000 switches and 1,000 none switches.
Results of 10,000 switches and 10,000 none switches.
Results of 10,000 switches and 10,000 none switches.

The main point of interest of these results is the percentages, and for anyone who wasn’t convinced of the solution to the problem these results clearly show that you have a greater chance of winning if you change from your original choice (as you’d expect). Also, we can see that the more games that are played the closer we get to the values of 1/3 (wins without switching) and 2/3 (wins with switching).

The Monty Hall Problem (Part 1)

This part of the post is about explaining the problem itself and why the answer is what it is, whilst the second part is about computing the answer and “proving” it. Therefore, if you are already familiar with the problem skip to part 2 of the post.

Since reading about the problem in a book when I was young, the monty hall problem, has always been something I have found interesting, and found myself on the Wikipedia page for it multiple times (including when it was used in one of Derren Browns shows, and in the movie 21). So I decided to write a program that demonstrates it and write a blog post about it.

The “Problem”

Imagine you are on a game show and the host shows you 3 closed doors and asks you to pick one – either 1, 2 or 3. You are told that behind 2 of the doors there is a goat, but behind one of the doors is a grand prize of a car. After you have made your choice, let’s say you choose door number 1, the host (knowing which doors contain the goats) will then open one of the doors you haven’t picked to reveal a goat. For this example let’s say he shows you door number 2. After, showing you the goat behind this door, you are then given the option to swap your choice to the remaining door if you wish.

The question is, do you have a better chance of winning if you stick to your original choice (door 1) or are you more likely to win if you switch (to door 3)?
Or worded differently:
What are the chances of the car being behind door number 1, and the chances of it being behind door number 3?

The Solution

It seems like the answer is obvious – there is a 50% chance of winning whether you stick with your choice or if you switch, and therefore switching has no benefit. This answer is actually incorrect, despite it seeming so simple and clear.

The fact is you actually have 1 in 3 (33.33%) of chance of winning if you stick with your initial answer BUT if you decide to switch your chances of winning increase to 2/3 (66.66%).

Explanation

The main reason the chance of winning changes from 1/3 to 2/3 is because the host has to choose one of the losing doors.
On my first choice there is 1 in 3 chance of picking the grand prize, and a 2  in 3 chance of picking a goat.
If I pick a goat on my first choice (which is more likely), the host will then show the door which doesn’t have the car behind it, meaning when I switch I will win the car.

The wikipedia page does a nice job of explaining why the odds change, or if you prefer here is a youtube video which explains why (Skip to 2m 40s for the explanation of why):

The second part of this post can be found here where I discuss the program I created based on the problem and the results it produces.