Friday, March 02, 2018

Guards in Java

Haskell functions have this nice concept called 'guards' which allow you to define a condition and return a value when that condition is true.

For example:

abs n
  | n < 0     = -n
  | otherwise =  n

This makes the code rather readable, especially when you have more guards.

Guards build one upon another since you know that if your guard condition is checked, all the other failed:

something n
  | n < -2 = 10
  -- bellow we know that n > =-2
  | n < 0 = 8
  | otherwise = n

Back in Java land, where I get paid, I sometimes wondered if I should write a method as:

X method(Y param) {
  if (!param.isSomething()) {
    return null;
  } else {
    return param.getX();
  }
}

or if I should write it as

X method(Y param) {
  if (!param.isSomething()) {
    return null;
  }

  return param.getX();
}

I generally prefer the 2nd variant and now I realised these are a form of function guards!



Guards in Java

Haskell functions have this nice concept called 'guards' which allow you to define a condition and return a value when that conditi...