Wednesday, 14 June 2017

An introduction to Refactoring Java in IntelliJ using RestMud as an Example

TL;DR Never too late to refactor. Do it in small chunks. Protected by tests. Using IDE to refactor.

My RestMud game grew organically, I do have a fair bit of Unit testing, but I also perform more integration testing than unit testing.

The good thing about this approach is that the integration testing represents requirements i.e. in this game I should be able to do X, and my integration tests at a game engine level create test games and check conditions in there.

These tests rarely have to change when I amend my code.

The side-effect of this type of testing is that the classes don’t have to be particularly good, so I have a lot of large classes and not particularly good organisation.

I’m now refactoring the classes and organising the code to have 4 main sections:

  • Game Engine
  • Games
  • API
  • GUI

At the moment I’m concentrating on the Game Engine.

I have a large main class called MudGame and I’m splitting that into smaller classes now.

Refactoring from Map to POJO

As an example my MudGame used to have a Map for locations, and collectables and messages.

This meant that I had 4 or 5 methods for each of these collections in my MudGame, I have now only a few high level methods in Game and most of the code has moved to the Locations, or Collections object.

As I was doing this I had to make a decision, do I make a public final field, or do I create a private field, with an accessor method.

I initially chose public final and amended the code, and then changed my mind to have an accessor method.

I don’t worry too much about this because it is easy to use IntelliJ refactoring to rename and wrap fields in accessor methods.

private Map<String, MudLocation> locations = new HashMap<>();

To an object that manages locations, which contains all the code methods that were on MudGame

public final Locations gameLocations = new Locations();

I chose to make the field public initially, then I refactored using “Encapsulate as Method”:

private final Locations gameLocations = new Locations();


    public Locations getGameLocations() {
        return gameLocations;

Refactoring Methods to Inline Code

Sometimes when I have a method that is small and doesn’t really add any value because I delegate all the functionality off to another Object, I might choose to inline it:

    public MudLocationObject getLocationObject(String nounPhrase) {
        return getLocationObjects().get(nounPhrase);

When I inline this then anywhere in the code that had:

MudLocationObject locationObject = game.getLocationObject(thingId);


MudLocationObject locationObject = game.getLocationObjects().get(thingId);

Some Tips for Refactoring

  • requirement level tests should not have to change during refactoring
  • make sure you have tests before you refactor
  • don’t worry too much about naming or field/method choices during initial coding because it is easy to refactor later
  • use IDE refactoring where possible
  • when code gets ugly, get refactoring
  • refactor in small chunks, keep chipping away,
  • refactor low hanging fruit first as it makes it easy to see what comes next
  • group code together to loosely organise prior to refactoring into new classes
  • Refactor Classes to represent semantics as well as helping organising code

It’s never too late to refactor your code.

Bonus Youtube Video

See also the accompanying YouTube Video:

In the video you’ll see:

An introduction to Refactoring Java in IntelliJ with a live demo using RestMud Game. I talk you through what refactoring is, and show examples of in built refactoring functionality in IntelliJ.

  • An introduction to refactoring
  • Basic Refactoring techniques and approaches explained
  • Refactoring from fields to methods with “Encapsulate Field”
  • Run tests after each refactoring
  • Check in code to version control frequently to allow reverting if things go wrong
  • Demonstration of refactoring
  • Explanation of intermittent Unit Test Execution
  • Sometimes as we refactor we discover we are creating duplicate code. When that happens, stop and decide if the existing code is good enough.
    -Try to avoid creating code that you aren’t using yet. You have to maintain it, and there are no tests,
    a nd you probably won’t use it in the future anyway!
  • Refactoring to Inline methods to remove methods completely. Remove the method and replace invocations
    with the code in the method
  • Reflect on your refactoring. Time to stop? Good enough to checkin? More to do?

Thursday, 13 April 2017

JSoup Tip How to get raw element text with newlines in Java - Parsing HTML and XML with JSoup

TL;DR with JSoup either switch off document pretty printing or use textNodes to pull the raw text from an element.

A quick tip for JSoup.

I wanted to pull out the raw text from an HTML element and retain the \n newline characters. But HTML doesn’t care about those so JSOUP normally parses them away.

I found two ways to access them.
  • switching off pretty printing
  • using the textNodes

Switching off Pretty Printing

When you parse a document in JSoup you can switch off the prettyPrint

Document doc = Jsoup.parse(filename, "UTF-8", "");

Then when you access the html or other text in an element you can find all the \n characters in the text.

String textA = element.html();

Use the textNodes

This approach works regardless of whether you have prettyPrint on or off:

String text = "";
for(TextNode node : element.textNodes()){
    text = text + node + "\n\n";

If you accidentally use both methods then you might get confused.

I think I prefer the second approach because it works regardless.

You can find code that illustrates this on github in the file

See also the accompanying YouTube Video:

Friday, 17 March 2017

Mistakes using Java main and examples of coding without main

TL;DR A potentially contentious post where I describe how I've survived without writing a lot of Java main methods, and how learning from code that is often driven by a main method has not helped some people. I do not argue for not learning how to write main methods. I do not argue against main methods. I argue for learning them later, after you know how to code Java. I argue for learning how to use test runners and built in features of maven or other build tools to execute your @Test code.

Monday, 5 December 2016

Let's Code - Binary Chopifier - Just Enough Code and Tooling to Start

TLDR; “Let’s code a Binary Chopifier” which I plan, code as prototype to plan in an @Test method, test interactively, experiment, and release as an @Test.

I want to create a few more examples of “Java in Action” and I’m doing that in some YouTube videos and blog posts that I think of as “Let’s Code”. First up is “Let’s code a Binary Chopifier” which I plan, prototype to plan, test interactively, experiment, and release to Github.

Let’s code a Binary Chopifier

When I was recording - Let’s Explore Google Search I made a note to write a binary chopifier.

In this series of videos we are going to create the binary chopifier and add it to Test Tool Hub.


First thing I did was make notes on what I wanted to support me in testing:

    Tool idea: binary chopper!
    start: 1024 end: 2048

    chop: value (inc)
        01: 1536  (512)
        02: 1792 (256)
        03: 1920 (128)
        04: 1984 (64)
        05: 2016 (32)
        06: 2032 (16)
        07: 2040 (8)
        08: 2044 (4)
        09: 2046 (2)
        10: 2047 (1)
        11: 2048 (0)

Explaining Binary Chop:
  • I try a value of length 2048
  • System doesn’t accept it because it is too long
  • I want to find the limit
  • I try 1024 (I binary chop 2048) and if that is accepted then
  • I try 1536 (midway between 1024 and 2048), and if that is accepted then
  • etc. until I narrow down on the value that is the limit
And if you watch the video you’ll see my mental arithmetic process was quite slow. I could spend the time boosting my mental arithmetic, or I could write a tool to help me.

Guess which is easier?

So I write a tool.

Thinking through an algorithm

The plan above represents a basic output to support me as the tester.

Really all I want is the chop and the value, but I used inc to help me calculate the chops
  • So I calculate the difference between the start and end: 1024
  • Divide it by 2 (chop) to get 512 then I add that to start (inc) and get 1536
  • And keep going.

Start by writing a ‘@Test’ which does this

I start by writing an @Test method which implements this algorithm and I can see if it works or not

public void calculateBinaryChopForStartAndEndFromThoughtAlgorithm(){

  int start = 1024;
  int end = 2048;
  int choppoint=start;
  int inc = start;

  while(inc > 0){

  inc = (end-choppoint)/2;
  System.out.println(String.format("%d (%d)", choppoint, inc));


Which gives me the output

1536 (512)
1792 (256)
1920 (128)
1984 (64)
2016 (32)
2032 (16)
2040 (8)
2044 (4)
2046 (2)
2047 (1)
2047 (0)

Which isn’t what I was looking for, but makes sense since on the last increment it is zero.
Perhaps then, inc isn’t inc it is diff between end and chop point.

So rather than ‘add to’ the start, I should ‘take away’ from the end

    public void calculateBinaryChopForStartAndEnd(){

        int start = 1024;
        int end = 2048;
        int choppoint=start;
        int inc = start;

        while(inc > 0){

            inc = (end-choppoint)/2;
            System.out.println(String.format("%d (%d)", choppoint, inc));


Which gives me my original plan:

1536 (512)
1792 (256)
1920 (128)
1984 (64)
2016 (32)
2032 (16)
2040 (8)
2044 (4)
2046 (2)
2047 (1)
2048 (0)

But since I’m working from the end, I’m wondering if what I actually do is just keep halfing the difference:

public void calculateBinaryChopForStartAndEndHalfDifference(){

  int start = 1024;
  int end = 2048;
  int diff = end-start;

  while(diff > 0){
  diff = diff/2;
  System.out.println(String.format("%d (%d)", end-diff, diff));

Which gives me:

1536 (512)
1792 (256)
1920 (128)
1984 (64)
2016 (32)
2032 (16)
2040 (8)
2044 (4)
2046 (2)
2047 (1)
2048 (0)

And is much simpler.

And since this ‘test’ is a useful ‘tool’ for me - I’ll stop there for this video. And next I’ll start refactoring this out into a library for binary chopping so that I can then use that in the Test Tool Hub.

Friday, 21 October 2016

How to create and release a jar to maven central

TLDR; The instructions on apache and sonatype site are pretty good to help get library released to maven central. But you’ll need to learn about pgp signing and might need more rigour in your pom file. A fairly painless learning process that I recommend you go through and release something to the world.

I spend most of my time with Java writing stand alone applications to support testing or code that we run as part of CI. I haven’t had to create a library that I make accessible to other people through maven central.

I thought it was about time I did so.

In this post I’ll describe what I did and how I got a .jar in Maven Central.

What is the Library?

As part of my Selenium WebDriver online training course I created a ‘driver manager’ to allow code to more easily run across different browsers.
It works fine for the context of my course.
Over time I’ve started splitting the course source into multiple parts:
And I’ve had to copy the into the continuous integration project.
I decided to pull it out into a separate library and make it accessible via maven central, that way it will be easier for people taking the course to use the Driver class in their own code.
And I can start maintaining it as a project on its own merits with better code and better flexibility, rather than something that just supports the course.

Summary of what to do?

What follows is a ‘checklist’ created from my notes about how I released.
Now that I have a groupid that will synchronise to maven central, it should be a simpler process if I want to create any future libraries.

A bit more detail

The documentation I linked to is pretty good. I mostly just copied the information from there.
And you can see the results in the released library code:
And the sample project that uses the library:

Changed my code to use minimal libraries

One change I made to the library pom.xml that is different from my normal use of the code in projects.
I decided not to include the full version of Selenium WebDriver - which I normally do when I use it:
Instead I wanted the minimum I could add, since I know that the projects using it will be incorporating the full version of Selenium WebDriver.
So I just used the Java Interface:

Configuring repositories in the pom.xml

I haven’t had to do this for a long time. I vaguely remember doing this in the past as a workaround for some local issue we had.
In order to access the -SNAPSHOT release version of the library I have to have the repository configured in my pom.xml
<!-- to use snapshot versionsof the driver manager we need to use the OSS nexus repo -->

        <name>OSSHR Staging</name>
I imagine that this might prove a useful workaround if I ever encounter a site that has configured the maven config via settings that we are unable to access easily.

Deploy was easier than I thought

I haven’t used the release deploy in maven before. And the instructions had a whole bunch of commands:
//perform a release deployment to OSSRH with

mvn release:clean release:prepare

//by answering the prompts for versions and tags, followed by

mvn release:perform
But in the end I didn’t have to do this.
I changed the version to remove -SNAPSHOT and it ‘released’ when I did a mvn clean deploy

Tagging a release on Github

I haven’t ‘released’ on Github before so I created a release via the github GUI on the releases page


What went wrong?

I tried to use a groupid that I don’t own

I’ve been pretty laissez-faire with my groupids in my projects and high level package names because I’ve never released one before.
But to use maven central you need to have a domain that you own.
And someone has snapped up the .com that I often use in my code, so I needed to use the that I own.
I might well start changing the code that I create to use this new groupid now :)

I put my group id the wrong way round

I tried mvn clean deploy for a snapshot release and I received:
[ERROR] Failed to execute goal org.sonatype.plugins:nexus-staging-maven-plugin:
1.6.7:deploy (injected-nexus-deploy) on project selenium-driver-manager:
Failed to deploy artifacts: Could not transfer artifact
:selenium-driver-manager:jar.asc:javadoc:3.0.1-20161020.083347-1 from/to
ossrh (
Access denied to:
ReasonPhrase: Forbidden. -> [Help 1]
I checked that my credentials were correct by logging into the oss nexus system
My issue was that instead of using groupid
I mistakenly used:
So don’t do that.

I forgot to release the gpg key

I forgot to release the gpg key when I created it, so I ended up trying to do a final release and seeing the following error during mvn clean deploy
[ERROR]     * No public key: Key with id: (xxxxxxxxxxxxx) was not
able to be located on
&lt;a href=;;/a&gt;.
Upload your public key and try the operation again.
Make sure you do this early in the process.
Also I had to wait 10 - 20 minutes before it was accessible.
To check, visit the site you uploaded to and then search for the key.
I had to search for the key id with 0x in front of it i.e.
  • 0x740585A4
  • and not 740585A4
When it was available from the search, then I could mvn clean deploy

Future work

I still have a lot to learn here.
As a beginner:
  • I’ve added a lot of ‘stuff’ to the pom.xml that I don’t fully understand and need to research
  • I’m sure I’m taggging the release on Github inefficiently
  • I’ve only done one release so I’m not sure if it is fully setup yet
  • I do this manually and haven’t added a CI deploy - when I do I’ll read the sonatype blog post more carefully
And I have an actual todo list:
  • I need to document the library and example in more detail if I want usage to spread beyond my course.
  • I need to amend my wdci and course code to use the library
But, it was a lot less daunting than I expected and the documentation was pretty clear, and the OSSHR team were very helpful in getting me setup, I was very impressed given that the oss staging repositories and syncing to maven central is a free service.
Hope that helps someone on the road to making their release. All in all it was a good learning experience.


Wednesday, 5 October 2016

New Java For Testers Install Videos and Checklist for Windows and Mac Released

TLDR; use the startUsingJavaJunit checklist on github to install Java JDK, and Maven, it also has links to ‘install tutorial’ videos for Windows and Mac

One of the hardest parts of writing a book, is keeping it up to date.

Particularly for install instructions.

Its one of the reasons, that Java For Testers has a checklist approach to the install instructions in the book. And why I have information on the website describing the install.

New Install Instructions

I have just updated the install instructions and videos online because:
  • Maven 3.3.9 has a slightly different install process (no need to create an M2_HOME environment variable, although nothing bad happens if you do, so the old instructions still work)
  • Mac, while ‘easy to use’, forces you to use the command line when installing development tools and people new to programming and command line find this hard - so the install instructions for Mac that I have on the web site, now use Homebrew.
  • IntelliJ GUI has changed enough, since the last time, I created the video that I receive questions on how to import projects
The install instructions are now supported by a Github project:
with an install checklist:
The project is basically a maven project with a single test, so when you run it, you can see that maven, and JDK are working on your machine.
I have install videos for both Windows and Mac:

Tuesday, 27 September 2016

How to fix IntelliJ issues by looking in the IntelliJ log

TLDR; View the IntelliJ log Help -> ‘Show Log in Explorer’

I experienced an issue when importing maven projects.

I found the answer to my problem on StackOverflow:
“…set Settings > Build, Execution, Deployment > Build Tools > Maven > Importing > JDK for Importer to Use JAVA_HOME…”
The above solution worked for me. But it made me realise that it is harder than it needs to be to find what is going wrong with IntelliJ if you don’t know one trick - how to view the logs with IntelliJ.