1 minute read

Last week I was working with a colleague on the implementation of a fairly simple validation of a character: the criteria for validation was that the character had to be lower case or a digit.

Looking at the Javadoc we spotted a couple of useful methods in the Character class: isLetterOrDigit -this method is pretty straightforward- and is LowerCase that returns false for upper case letter and everything is not a letter.

The code we wrote looked like:

if (!isLowerCase(aCharacter) &&!isDigit(aCharacter)) {
    //error !!

All the tests passed. Fairly simple and coincise solution.

But..are we actually expressing the business requirements ?

No. Not al all.

Our code is not communicating clearly what we’re trying to achieve: the API is not clearly expressing that punctuations are not allowed.

The expected behaviour is there but the code is still not in an ideal shape: we need to be able to clearly express what we really need to validate.

The refactored code looked like:

if (!isALowerCaseCharacter(aCharacter) && !isDigit(aCharacter)) {

where isALowerCaseCharacter was:

private boolean isALowerCaseCharacter(char aCharacter) {
    return isLetter(aCharacter) && isLowerCase(aCharacter);

This is better. We are might be increasing the actual complexity of the condition but our code is now expressive: if in 3 months time we pick up this code again we clearly know what business rule we’re applying without looking at <any< additional resource.

The code now is communicating our intention.