Monday, January 1, 2018

few defensive coding techniques

Here is a guide to a few guarded (defensive) coding techniques:

(1) Guarding against string nulls

if (StringUtils.isNotBlank(inputString)) {
    // Process
}

Will return false if inputString is blank, spaces or null

(2) Guarding against empty List

A list may be not null, yet it can be empty – to check if the list does contain any elements

If (list != null && !list.isEmpty) {
        // Processing
}
Note: If an instanceof check is present, an extra null check is not required

(3) Boolean  can have 3 values (not 2) – true, false and null.

So, Boolean isVerified = getVerified(…)

Assume isVerified is null, in that case below would fail.

if (isVerified)  {
         // process
}


Instead:

BooleanUtils.isTrue(Boolean.TRUE)  = true
BooleanUtils.isTrue(Boolean.FALSE) = false
BooleanUtils.isTrue(null)          = false


if (BooleanUtils.isTrue(isVerified)) {
      // process
}

(4) A list contains different objects 

Say, List fruits = new ArrayList();
fruits.add(new Apple())
fruits.add(new Orange())

while (iterator.hasNext()) {
    Apple apple = (Apple) iterator.next() ; This code will fail with a classcast
}

Adding instanceof check:

while (iterator.hasNext()) {
            Object o = iterator.next() ;
            if (o instanceof Apple) {
                        Apple apple = (Apple) o;
            }
}


(5) Ensuring numeric checks are present

Backdrop: Say the following code can fail with a NumberFormat if the ageofdriver is not numeric

int driverAge = Integer.parseInt(ageOfDriver);

One of the defensive way of writing that would be as follows:

if (StringUtils.isNotBlank(ageOfDriver) && StringUtils.isNumeric(ageOfDriver)) {
      int driverAge = Integer.parseInt(ageOfDriver);

}

No comments:

Post a Comment