Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Best Practices in Ranges



Ranges are very useful in Groovy based development. We can keep best practices in mind to use them effectively. In this chapter, we're discussing best practices while using the ranges.

Select the right type

Ranges can be of multiple types in terms of exclusivity.

  • Inclusive Range - A range defined using start..end can be used when we need to include both starting and ending values of the sequence. It is commonly used when we need to perform certain set of iterations.

  • Exclusive Range - A range defined using start..<end can be used when we need to exclude ending value of the sequence. It is commonly used when zero based collections are used.

  • Exclusive Beginning Range - A range defined using start<..end or start<..<end can be used when we need to exclude begining of the sequence. A exclusive beginning range functionality is avaliable from Groovy 4.0+ onwards.

Utilitize Range methods

There are many useful methods on ranges as shown below.

Sr.No. Methods & Description
1 contains()

Checks if a range contains a specific value

2 get()

Returns the element at the specified position in this Range.

3 getFrom()

Get the lower value of this Range.

4 getTo()

Get the upper value of this Range.

5 isReverse()

Is this a reversed Range, iterating backwards

6 size()

Returns the number of elements in this Range.

7 subList()

Returns a view of the portion of this Range between the specified fromIndex, inclusive, and toIndex, exclusive

8 toArray()

Returns an array of elements of this range.

9 step(stepSize)

Returns a new List using the steps on the elements of the range with specified interval

10 toList()

Returns a list of elements of this range.

Use Ranges for Iteration

Following example shows various features of ranges useful in iterations.

Example.groovy

class Example { 
   static void main(String[] args) { 
      // Inclusive loop 
      for (i in 1..5) {
         println i
      }

      // Exclusive loop to iterate a list
      def myList = [10, 20, 30, 40]
      for (i in 0..<myList.size()) {
         println "Element at index $i: ${myList[i]}"
      }

      // Using step to get even numbers
      for (i in (0..10).step(2)) {
         println i // Output: 0, 2, 4, 6, 8, 10
      }

      // Using each for a range
      (1..3).each { number ->  println "Number: $number" }	   
   } 
}

Output

When we run the above program, we will get the following result −

1
2
3
4
5
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
0
2
4
6
8
10
Number: 1
Number: 2
Number: 3

Implement next() and compareTo() methods for Custom Objects

In case of ranges for custom object, implement the Comparable interface and implement next() for progression. It helps groovy to define a correct order and generate proper range of custom objects. Visit Custom Ranges for more details.

Idiomatic Approach

It is always good to use range methods like each, collect, findall over tranditional loops like for, while to iterate the range. It helps in making code more readable and maintainable.

Use Ranges for Iteration

Following example shows various features of ranges useful in iterations.

Example.groovy

class Example { 
   static void main(String[] args) { 
      // define a range of numbers from 1 to 10
      def numbers = 1..10

      // get and print even numbers using step and each
      numbers.step(2).each { println it }

      // get a list of squares and print
      def squares = numbers.collect { it * it }
      println squares

      // Check for a specific number
      if (numbers.contains(5)) {
         println "The range contains 5"
      }

      // get a sublist
      def firstThree = numbers.toList()[0..<3]
      println firstThree
   }
}

Output

When we run the above program, we will get the following result −

1
3
5
7
9
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
The range contains 5
[1, 2, 3]
groovy_ranges.htm
Advertisements