Skip to main content

Posts

Showing posts from September, 2016

Java Generics Return type refactoring exercise

One of my more interesting tasks of the past few weeks was to refactor an existing method to use Generics in a method's return type and simplify the readability of code that calls the method. The starting point was this method: public static Object getHandler(Class<?> aClass) throws HandlerException  {    if (handlerFactory == null)       handlerFactory = new HandlerFactory();    return handlerFactory.getHandler(aClass); }

Java 8: Rewrite For-loops using Stream API

Java 8 Tip: Anytime you write a Java For-loop, ask yourself if you can rewrite it with the Streams API. Now that I have moved to Java 8 in my work and home development, whenever I want to use a For-loop, I write it and then see if I can rewrite it using the Stream API. For example: I have an object called myThing, some Collection-like data structure which contains an arbitrary number of Fields. Something has happened, and I want to set all of the fields to some common state, in my case "Hidden"

Unit Testing Tip: Break steps into separate methods

Testing in the Trenches (TinT) is a series of posts adapted from real-world discussions and advice I have given to teams and individuals struggling to adopt Unit Testing habits and best-practices. The Method is an important basic unit of unit-testing. If you have a tendency to write entire processes or algorithms as single, large methods, you will find a lot of benefits to breaking them into smaller steps in separate methods. Unit tests for these smaller methods are easier to write, and are key for proving the validity of each step in the larger process. For example: We have an Enhancement Specification that says the program should behave one way if a given Rule has never yet been applied, and behave another way if the Rule has already been applied one or more times. This distinction of "already used or not" is a key condition that appears many times in this spec. We can check for the condition with something like this: if (myrecord.getAsString(lastPledgeDate