Thursday, September 15, 2016

Replace switch statements using lamda's

Complex switch statements with many possible cases tend to result in cluttered code. When code checkers start to complain about the complexity of a method, it becomes time to refactore that piece, but often that sounds simpler than it actually is.
With lambda's in java 8 these switch statements can easily be simplified resulting in cleaner, easier to read code.
Lets take for example the below switch statement and turn that into a nice and easy to understand piece of code using a Map and some lamba expressions.

public List<string> findUsingSwitch(Bicycle bicycle) {
  switch (bicycle) {
    case RACE:
      return listRacers();
    case ATB:
      return listAtbs();
    case CITY:
      return listCityBikes();
    case HPV:
      return listHumanPoweredVehicles();
    default:
      throw new IllegalArgumentException();
    }
}

Its easy to imagine that such a switch statement can grow and become pretty complex.
In java 8 we now have the ability to use lambda expressions and pass them around to functions. This allows us to replace the switch/case block with a more flexible and more natural implementation.
Lets first start with creating a map that associates the enum with the lambda that produces the result for the given enum value.

private Map<Bicycle, Supplier<List<String>>> typeMap = new HashMap<Bicycle, Supplier<List<String>>>() {
  {
    put(Bicycle.RACE, () -> listRacers());
    put(Bicycle.ATB, () -> listAtbs());
    put(Bicycle.CITY, () -> listCityBikes());
    put(Bicycle.HPV, () -> listHumanPoweredVehicles());
  }
};

Now the find method can be changed to use the lambdas instead:

public List findUsingLambdas(Bicycle bicycle) {
  if (!typeMap.containsKey(bicycle)) {
    throw new IllegalArgumentException(String.format("%s is not supported", bicycle));
  }

  return typeMap.get(bicycle).get();
}

The sources can be found on github.

Replace switch statements using lamda's

Complex switch statements with many possible cases tend to result in cluttered code. When code checkers start to complain about the complexity of a method, it becomes time to refactor that piece, but often that sounds simpler than it actually is.
With lambda's in java 8 these switch statements can easily be simplified resulting in cleaner, easier to read and extend code.
Lets take for example the below switch statement and turn that into a nice and easy to understand piece of code using a Map and some lamba expressions.

public List<string> findUsingSwitch(Bicycle bicycle) {
  switch (bicycle) {
    case RACE:
      return listRacers();
    case ATB:
      return listAtbs();
    case CITY:
      return listCityBikes();
    case HPV:
      return listHumanPoweredVehicles();
    default:
      throw new IllegalArgumentException();
    }
}

Its easy to imagine that such a switch statement can grow and become pretty complex.
In java 8 we now have the ability to use lambda expressions and pass them around to functions. This allows us to replace the switch/case block with a more flexible and more natural implementation.
Lets first start with creating a map that associates the enum with the lambda that produces the result for the given enum value.

private Map<Bicycle, Supplier<List<String>>> typeMap = new HashMap<Bicycle, Supplier<List<String>>>() {
  {
    put(Bicycle.RACE, () -> listRacers());
    put(Bicycle.ATB, () -> listAtbs());
    put(Bicycle.CITY, () -> listCityBikes());
    put(Bicycle.HPV, () -> listHumanPoweredVehicles());
  }
};

Now the find method can be changed to use the lambdas instead:

public List findUsingLambdas(Bicycle bicycle) {
  if (!typeMap.containsKey(bicycle)) {
    throw new IllegalArgumentException(String.format("%s is not supported", bicycle));
  }

  return typeMap.get(bicycle).get();
}


The example sources can be found on github

Sunday, December 20, 2015

Agile culture at spotify

Here are some interesting vid's showing the development culture at spotify, a very interesting variation of scrum organizing development teams.
I think this could work great for companies continuously improving a product or suite of products. But does this also work work for single independent projects? Perhaps its better to stick with the pre defined scrum practise in those cases.

Monday, November 02, 2015

Unit testing a Spring MVC REST service

Properly testing a Spring MVC based REST service controller is made easy using MockMvc.
Validating the results is made easy using both JsonPath and XmlUnit

Tuesday, June 09, 2015

Removing files from svn without removing from the file system

Every now and then it happens that I have shared a project to subversion and noticed that while committing a number of files have been added (albeit not yet committed) to subversion.
Excluding these files from the commit only solves that problem temporarily, with the next commit these same files are again presented as changed files.

Removing these files from the local subversion administration is not hard, but each time I find myself searching again for the correct command, so today I decided to spent a blog on it, although the actual content is just a one-liner:

svn rm --keep-local

This will remove the file from subversion but will leave the files on the file system. This is quite useful with IDE files for instance.

Wednesday, November 19, 2014

Installing a JDK on windows without admin rights

Here at the office I do not have admin rights.
This is a pain because I cannot update the JDK to a version I'd like/have to use.
Well there is an option.

Download the desired JDK from the regular location.
Open the executable file using 7-zip or something similar. The executable contains only a single file named tools.zip. Unzip that file to a location where you want the JDK installed and you have write access to, for instance c:\development\jdk-8.20.
This will create the installation structure, although many of the jar file components are still compressed. These must be de compressed using a tool provided with the JDK itself, unpack200, that is found in jre\bin.
Locate all .pack files using dir *.pack /s/b and de-compress each of them using upack200:

c:\development\jdk-8.20\jre\bin\unpack200.exe -v -r path\file.pack path\file.jar.
The '-v' option provides for verbose output and the '-r' option removes the original pack file afterwards.

Tuesday, August 05, 2014

Mocking the InitialContext

Unit testing with JNDI

One of the issue's with unit tests is that it is not always easy to control the java.naming.InitialContext provided to the object under test.
Mock frameworks cannot create mocks for JRE classes like InitialContext, so how can we solve this challenge?

One solution could be to create a simple implementation for the javax.naming.spi.InitialContextFactory that returns a mock implementation provided by mockito. Through configuration, our implementation is then used.

public class InitialContextFactoryMock implements InitialContextFactory {

  private static Context mockContext;

  /**
    * The mockContext is created here to be able to use the {@link Context}
    * mock object while defining the expectations.
    * Remember to call this method each time a new test case is run.
    * 
    * @return a fresh {@link Context} mock.
    */
  public static Context getMockContext() {
    mockContext = mock(Context.class);

    return mockContext;
  }

  /**
    * This factory returns the {@link Context} mock created earlier.
    */
  public Context getInitialContext(Hashtable environment) throws NamingException {
    return mockContext;
  }
}

To use the InitialContextFactoryMock you need to specify it in the jndi.properties:


java.naming.factory.initial=the.mocks.InitialContextFactoryMock

Friday, November 09, 2012

Free IT related ebooks

From a post on the LinkedIn Open Source Group, I've got this link pointing to a lot of free IT related ebooks, without to go through data-harvesting sites: http://cfajohnson.com/computers/pdflinks.shtml?

I hope this is helpfull to anyone else.