Sunday, August 12, 2012

Groovy Day 1 : Truth (2/2)

The second part of the post on Groovy Truth is about collections and custom conversion to boolean. First the collections, in Groovy, a collection can be tested for nullity and emptiness at the same time.
List list1 = [2,3,5] // way that groovy declare List, in this case, an ArrayList is used
List list2 = [] // empty list
List list3 = null

assert list1 // test is the object is null, if it's not the case, test emptiness on collections
assert !list2 // the list is non-null but empty
assert !list3 // the list is null

Just take care that !list2 returns false but the list exists, we can't use that way to test if we can add item to that list by example. Problem: what to do when we want to know if the list is empty but non null ? or just null ?
assert !list1?.empty // equivalent of (list1 != null && list1.empty)
assert list2?.empty
assert !list3?.empty

assert !(list1 == null) // just test if null
assert !(list2 == null)
assert (list3 == null)
Second part: how to customize the different tests, like the collection that use the emptiness for the truth. There is a method that is called by Groovy after the test on nullity. The method is called asBoolean. Let's make a simple example:
// Class that can be tested in condition, is true only if the internal value is 100
class FullLife{
   private int val

   boolean asBoolean(){
      return val == 100
   }
}

assert !new FullLife(99) // not 100 => false
assert new FullLife(100) // equals 100 => true
This method is quite useful when you want to implement a custom collection or special items. But be careful that operator overloading is not a really good practice in general case, if the operator is not natural, avoid it. A good example of operator overloading is a Graph that can received Node by using the "+" operator. Bad example: Bulb++ means we want to turn on and Bulb-- to turn off. More on operator overloading in future tutorials.

No comments:

Post a Comment