Saturday, November 1, 2014

Your Great Code

Great code does not come from code reviews, code quality reports, using the latest tool or programming language.  Great code is built by developers who care about their work…

Where does this passion for code come from?  It comes from within.  Somewhere in your past this attitude or culture was impressed upon you. It makes up your value system, your personal philosophy.   

My journey began working on my first car with my Dad.  My feeble attempts to tape and rig my car into working order didn’t work.  Most of my repair attempts just made things worse.  Dad impressed on me two lessons;


  • If something is worth doing, it is worth doing right
  • Finding the correct way to fix a problem is always the best solution

We purchased a shop manual for the car and made regular trips to junk yards. Understanding the mechanics of the car and obtaining the correct parts made a big difference in my repairs.


I attended a small liberal arts college in Rome, GA - Berry College. All students were encouraged to work on campus.  My job was helping our stonemason in the repair and caring of the stone walkways and walls that made up parts of the campus.  I mixed concrete and hauled stones.

I learned to mix concrete and select the right stones for a repair. I also discovered that helping getting the correct slope on a walk way so rain doesn't pool imparted a degree of satisfaction. I learned the value of work done well.

Berry has a student code, during my college days it seemed like a relic from the past.  Time has helped me understand its wisdom.


"I promise not to be content with slip-shod or merely passable work.  I will take an interest in all my work and learn to do the right thing in the right way".
- The Berry Code circa 1920

How did you learn to care about your code?

   

Friday, August 15, 2014

Java 8 Mixin

Java 8 introduced default interface methods. These allow an interface to provide a "default" implementation of a given method.  The default methods are used in Java 8 to add new behaviors to collections (mostly around streams) without breaking existing implementations.

Default methods also open Java to the type of language construct known as a mixin (ruby) or trait (scala).  This blog post illustrates using default methods to add comparison behavior in a class.

Problem to solve...

Java has a cumbersome API used to compare objects.  The compareTo method returns an integer whose value and sign defines if the objects are less than, equal to or greater than each other.  I want to improve this by defining a interface that has default implementations of isLessThan, isGreaterThan and isEqualTo mixin methods.  I want to be able to simply take a class that already implements Comparable and change the interface it implements to one with these new default methods. 

To demonstrate this concept I'm going to use a Zombie domain class.  The type of  a zombie defines how it compares to other zombies.  The hierarchy is as follows: Walkers are less than Runners, which are less than Fatties, which are less than Abominations (nod to Zombicide).

This first version of the Zombie class implements the Comparable interface and implements the corresponding compareTo method.  The test for the class ensures the compareTo method works based on the integer and sign returned from the method.


Solution...

This test illustrates the issue I want to fix.  To determine if one zombie is bigger than another I need to check the returned value.  This makes the code difficult to read especially for developers not familiar with the compareTo function.  It is not a fluent API.  I can improve this using an interface with some default methods.

This interface will add the methods I am looking for to my Zombie class - it could add these methods to any class that already implements Comparable. The technique used here is that I am referencing a method that the class already has - compareTo, and expanding how it can be used.

The final listing shows that Zombie now implements Compares, and no additional changes.  The tests now use the new isLessThan, isGreaterThan and isEqualTo default methods.

Wrap-up

Default methods add another technique you can use to mange cross cutting behaviors in your classes.  At first glance they seem to be a hack used by the API designers to extend the old Java APIs.  I think they are solid addition to the language.

Sunday, May 11, 2014

Agile - where to start?

Understanding Culture
If you ask me about the culture of running I shouldn’t start by telling you to do long slow runs on Sundays. While long runs are part of the story they are simply a practice. No, I need to give you some context by describing the values or principles of running. Maybe the idea that runners (vs. joggers) value running as a sport - beyond just fitness. Runners come in all speeds but they push themselves to improve - which is a principle. Doing longer runs is a training practice that can improve your ability. Traditionally, runners do long runs on Sunday but you can do them on other days.


You understand the culture based on the values and principles. The practices make sense within the larger context. You better understand why the long run is important. What if all your training runs are the same distance (you don't do long runs) are you really a runner? Well, if you believe in the values and follow the principles - then yes.



This idea can expressed as follows: Culture = Values + Principles (which are expressed through practices)



Understanding Agile Culture
I believe the same is true for understanding agile software development. Often we start by talking about stand-ups, stories, automated testing and all the other practices without setting the larger context. First you need to understand the culture (values and principles) before comprehending how they are expressed by practices.


Agile software development, as a culture, is defined by the Agile Manifesto. The four values and twelve practices define what and how we seek to achieve a goal. Missing these fundamental ideas leads to an incomplete understanding. Why not count "development complete" stories as progress? Because we value working code and believe that is the only measure of progress.


Start with understanding the agile values and principles
There is a lot of content about agile software development.  Lots of cool ideas, ways to communicate, retrospect, organize and enable successful projects - you can quickly lose your way and miss the big picture.


So, start your journey at the Agile Manifesto site and branch out from there. First learn the basics then understand how the practices fit together and enable the principles and values. Oh, and try to get in your long runs maybe a running partner (or pair?) that can help your focus and commitment.

Saturday, April 26, 2014

Hamcrest Matching with Lambdas

Using Hamcrest matchers within your JUnit tests is a great way to create understandable, fluent tests.  You can make this test matching special by creating your own matchers specific to the objects you are testing.

In this blog post I will show you how to author custom Hamcrest matchers.  I'll also show how lambdas can make these custom matchers simpler to code and a bit more expressive.

Set-up

I'm using Java 8 in my example.  You will also need to include the appropriate Junit and Hamcrest jars.  The normal Junit jars come with a small portion of the Hamcrest matchers included as a dependency.  I suggest using the Junit jar without Hamcrest and including the full core Hamcrest as a seperate dependency.

My build.gradle file, notice the junit and hamcrest dependencies.

apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    testCompile 'junit:junit-dep:4.+'
    testCompile 'org.hamcrest:hamcrest-core:1.+'
}

In my example we are killing zombies, my Zombie class is here.

Custom Hamcrest Matcher

There are a couple of abstract classes you can use from Hamcrest to build your custom matcher.  I'm using TypeSafeMatcher<T>, the generic is the class for which you are creating the matcher.  This method creates a custom matcher that asserts the type of zombie.

Hamcrest ensures your target object is the correct type and is not null.  The remaining methods to create are:
  1. protected boolean matchesSafely(Zombie zombie)
    This is where you do the actual matching to ensure the actual result matches expected.
  2. public void describeTo(Description description)
    These methods are used to build a failure message (see in red below).  This method creates the first line - "Expected: <description>"
  3. protected void describeMismatchSafely(Zombie zombie,    Description description
    This method creates the second line - "but: <description>"
java.lang.AssertionError: 
Expected: Zombie should be ABOMINATION
     but: was WALKER

Test Class using Custom Matcher

Custom Hamcrest Matcher using Lambdas

All good stuff and leads to expressive tests.  However, all the boiler-plate code around the custom matcher is tedious.  This is where lambdas can be used to simplify the custom matcher.

First: create a generic matcher that accepts lambdas.

This class is a template that can be used in multiple custom matchers.  It allows you to use lambda expressions in place of the custom matcher methods.

matchesSafely becomes a Predicate function
describeTo becomes a Consumer function
describeMismatchSafely becomes a BiConsumer (two argument consumer)

Using this class you can instantiate custom matchers with much less code.

Revised Zombie matcher using lambdas and the templates matcher class.

This class implements three custom Zombie matchers in the same space as the original version used to implement one custom matcher.


Monday, February 10, 2014

No Null Checks: Use Optional

I have a method that can return a null value.

Use the return type of Optional to let callers know they need to handle absent values.


In this example the null check is needed because the city code may not exist in the repository.

However, it is not clear from the findCity method that a null could be returned.  

When it is possible for a null to be returned from a method use an Optional wrapper class to let the caller know what to expect and that they need to handle the case where the value is absent.

The optional class contains the instance that can be null and offers several convenience methods to elegantly handle the null condition.  Java 8 users should use the java.util.Optional version - since it is integrated into the various Java 8 APIs.  For other users there is a version in the Google Guava framework. 

Refactoring the null check example results in the following new implementation.

By returning Optional from the findCity method we are explicitly letting callers know that we might not find the city based on the code. There are a lot of interesting methods you can use on Optional to deal with missing values - here are a couple to get you started.

No Null Checks: Common Null Argument Checker

I want to fail fast when arguments passed into my method are null.
Use a common null check method to fail fast when input arguments are null.


This example is explicitly checking if the employee instance and throwing the NullPointerException to quickly fail the method call.

There are several utility classes that can implement this logic for you.  Both Java 8 and Google Guava include an Objects class that encapsulates and exposes this logic in different ways.

However, my preferred solution is to use the Lombok framework's @NonNull annotation. If you are not using Lombok get on-board…and stop bellyaching about how Java is so verbose!

This is what it looks like:

With this annotation if the generatePaycheck is invoked with a null employee reference a NullPointerException is thrown.

With the Java 8 Objects class the following checks are possible. Note, I did a static import on the Objects class - I believe this improves the readability of the code.

Don't make these checks a default for every method. Review where you put these types of checks in your code. I have seen teams go overboard, checking for nulls at every turn.

If it is a private method do you really need the null check?
Why are you processing null references in the first place?

No Null Checks: Use firstNonNull method

When a reference is null I need to use a default value.
Use a common method to encapsulate selecting the first non null value.


In this example I am getting a package quantity for a product.  Since the data is not perfect, I use either the quantity, inner pack quantity or a default.  Since this method is in a domain object this is the only place this logic lives.

There are several firstNonNull methods you can use.  The one below is from apache commons and uses a variable argument parameter - so you can pick between many fields for the first non null value.  The one downside is that it returns null if all the values are null.  Be use to include a constant default in the group.


Another option is to roll your own utility method using lambdas.

The findFirst function returns an instance of Optional. The terminating get method call is on the Optional and throws a NoSuchElementException if all the arguments are null.

No Null Checks: Use Optional and supplier functions

I need to call a getter on an instance that might be null.
Use Optional and supplier functions to navigate an object chain that may contain nulls.

Here I am trying to return the Street portion of an Employee's address.  If anything is missing I will use an empty string as the Street name.  But I need to check for nulls at every turn.  This results in a nasty triple nested null check.

This is a common pattern, other languages have a null safe getter construct that can be used.  Groovy has the elvis operator - ?. that will simply return a null.

With Java 8 you can use the Optional class with the map method to navigate the object chain.

Simply chaining these map calls together and using the method literal you can safely navigate this object chain. The revised method is significantly less complicated - which is a good thing.

No Null Checks: Use Comparator null handling

I need to sort on a field that could be null in some object instances.  Use Comparator null handling to compare instances that can be null.

In this compareTo method I have some employees without middle names.  So, if the first and last name are the same the sort will take into account the middle name - which could be null :-(

I'm going to clean-up this method by using the Comparator class from Java 8.

The Comparator defines a fluent interface that is used to build a comparator for multiple members of a class.  The secret sauce is the easy way it sorts nulls before or after non-null values - when both instances are null they are considered equal.

This update creates a separate comparator instance that is then used in the compareTo method. The null check is tucked away neatly within the Comparator.nullsFirst method. Also note the use of method literals to define the members of the Employee classes used for the compare.

I'm a recovering null checker...

That is right, in the past I explicitly checked references to see if they are null…yea, I still have lapses, I try to avoid it - null checks are insidious in a Java code base; and by insidious I mean:
  1. Are harmful but enticing.
  2. Hey, I got a null pointer exception (NPE) when running this test. Hmm, not sure if the data is right…oh well I can just add a null check here. The check will ensure the problem will not occur again.

  3. Spread harmfully, in a subtle or stealthy manner.
  4. Similar to other types of broken windows in a code base one null check begets another. Everything starts to be confusing…
    This variable was checked for null in this method so if I pass it to this method I need to check for null here as well. Quickly you have the problem of accidental, not real complexity.

  5. Have a gradual and cumulative negative effect.
  6. Individually they are not a big deal. Sure, it is not clear if it is an expected condition or just a enticing precaution someone coded. But, at some point the complexity null checks add to a codebase are over-whelming and they are a common theme in many bugs.
So, are Java null checks evil? Often they are (or at least a bad idea) and you need an approach (or two) to dealing with null values in your coding efforts.

I've been seeking better ways to deal with nulls for a while. This series of blogs distills these ideas into a catalog of approaches.  Please leave feedback if you think I've missed one or you know a better way.


I have a instance of a class that might be missing, in which case the reference is null.

In this example when the employee's jobRole is unassigned we say he is not due for a raise.  So, jobRole can be null. Now, to not get into trouble, everywhere we reference jobRole it needs to include null check. Obviously it is not DRY and the business rules for an unknown jobRole is strewn all over your codebase.

Fix; create a instance of the object to use when you are missing the item - known as the NullObject pattern.

Use the NullObject pattern in place of null checks.



I have a method that can return a null value. 

In this case we simply might have bad data or the repository has not been updated with a new city.

It doesn't seem bad for a validate method to check for null but what about other calls to the findCity method?

Hopefully callers will know to check for null - I'll just put it in the java docs ;-)

Use the return type of Optional to let callers know they need to handle absent values.

I want to fail fast when arguments passed into my method are null. 

Yep, very common - let us fail quickly not 5 frames into this method where it could be difficult to see the employee was null from the start.

Of course there is a better way to encapsulate this idea.


When a reference is null I need to use a default value.

In this example I'm getting a package quantity for a product.  I need to use the first non-null value either quantity, inner pack quantity or a default value.

I need to call a getter on an instance that might be null.

Here I am trying to return the Street portion of an Employee's address.  If anything is missing I will use an empty string as the Street name.  But I need to check for nulls at every turn.  This results in a nasty triple nested null check.


I need to sort on a field that could be null in some object instances.

In this compareTo method I have some employees without middle names.  So, if the first and last name are the same the compare will take into account the middle name - which could be null :-(

Yes, this is an ugly compareTo implementation - there are various utility methods that can be used to improve it - I'm going to use the Java 8 API.


Monday, January 13, 2014

No Null Checks: Null Object Pattern

I have a instance of a class that might be missing, in which case the reference is null.
Use the NullObject pattern in place of null checks.


The null object pattern seeks to use an alternative, default or no-operation instance in place of a null
reference.  Instead of having an object reference point to null it points to the "default" or "missing" instance.

The default instance needs to be able to be able to stand-in for the real instance within the code base.  Code using the default instance should be able to call methods and interact with a default instance and produce the correct results (the Liskov substation principle applies).

Example Using a class
In the JobRole class example above we need to create a "null object" stand-in.  Here I create an UnknownJobRole class that extends JobRole.  The class that instantiates the Employee object graph then needs to know to use the UnknownJobRole class when an employee does not have a JobRole.  This class will override any method in JobRole so it can be used in its place.

This code returns false for the two methods I have in the JobRole class. This seems reasonable but in some cases is difficult to assign a default value for missing data.

Now that I don't need to worry about the jobRole instance being null I can revise my method.




Example Using Enum
When defining Enums, if the value could be missing be sure to add a default or unknown value. These null object enums are also handy if you need to sort a collection instances by the enum value. Remember enums will sort based on their ordinal (the order they are defined within the enum class).




Using a collection
A simple way to avoid null checks for collections is to always use an empty collection. A empty collection can be viewed as a type of null object pattern implementation. The Collections class in Java 8 has been expanded to include several convenient methods to help with empty collections.



Summary
The null object pattern is the place to start when dealing with null values, especially in your domain classes. It is an elegant solution to the problem. However, it doesn't work for every situation and can introduce needless complexity.  Pick the right solution for the problem at hand and don't let anyone tell you the Null Object Pattern is the only correct way to deal with nulls.

Wednesday, January 8, 2014

Refactor: Extract if statements to Enum + Lambdas

This post is a follow-up to my Refactor: Extract if statements to Enum post.  In this entry I make the enum implementation a bit more concise using Java 8 lambdas.

In the previous blog we refactored the "if logic" into an enum.  The FrameType enum then knew how to calculate the score for the frame with the appropriate point bonus for strikes and spares.

Now I want to specify the logic as a functional interface. This approach expresses the same logic but in a condensed style without the ceremony overriding an abstract method. I have also refactored the rolls in frame to be a member variable - which is convenient using the enum constructor.

The scoreFrame logic is moved into a java.util.function.BiFunction instance. BiFunction<T, U, R> is a function that takes two objects, of type T and U. and returns an Object of type R. The lambda is supplied as an argument in the constructor and kept as a member of the enum instance.

The scoreFrame method changes from abstract to simply applying the function and returning the result. No changes in the BowlingGame class that uses the enum.

The result is a bit more concise, we have overcome some of the vertical space needed to express the old solution.  Does it read better?  Is it clear what the lambda does?  Let me know what you think…is it better?

Monday, January 6, 2014

Refactor: Extract If statements to Enum

When a method's logic gets complex it can indicate we are missing an abstraction.  In this entry I highlight how Java's enum can be a simple abstraction that simplifies your logic and improves
code readability.  As a starting point I use a class from the bowling game kata.

Additional background information about the bowling game kata can be found here The Bowling Game Kata.

The refactoring step applied introduces an enum to represent the frame type and moves the scoring logic to the enum instance.  This simple technique can be used to simplify code by adding simple abstractions.

I'm going to focus my refactoring on the score method (which scores a bowling games based on the frames bowled) that at the end of the kata looks like this:

The score method has a nested if else statement that I would like to simplify. Often, when code seems complex it can indicate you are missing a concept. In this case I think introducing a class that represents the type of frame reduces the complexity and makes the code easier to understand. The FrameType enum represents how the player scored in a Frame - Strike, Spare or Open (meaning not all the pins were knocked down). The classifyFrame method determines the applicable type based on one or two rolls.


Now that I can classify the frame I think the enum should know how to compute the score for the frame. Since each FrameType instance has a slightly different score calculation I am defining an abstract method within the enum. Then each enum instance will define its specific implementation.


This is the final version of the class. The rollsInFrame method is another behavior that is specific to each frame type. As you can see this refactoring removed the if else structure from the method. The score method now highlights the top level logic and the details are in the enum.

Introducing an enum is a simple way to encapsulate different logic into objects versus using if statements (a OO technique called polymorphism). In the right context this is a powerful tool to simplify and improve code readability.  Using an enum is a simple way to introduce a new object and harness polymorphism.  If your needs evolve the implementation can become classes and that inherit from a FrameType super class.  There is nothing in the code that calls the scoreFrame method specific to our chosen enum solution.

At a high-level most people know that in bowling spares and strikes are scored differently. The BowlingGame class now tells that story.

Can we do better?

The score method seems ok - it is expressive, the level of abstraction is the same for each statement.  I don't always like using the += operator.  Why is the enum called FrameType? Is there a better name?

The FrameType enum makes sense, I think it reads fine.  It does seem horizontally challenged.  There are a lot of statements, somewhat due to Java language constructs.  What other options do we have?  Maybe functional lambdas?