HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Better way to assert correct return values in Groovy

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
returnwaybetterassertcorrectvaluesgroovy

Problem

I have written a function that returns me the duplicates of a list:

static List findDuplicateElements(List myObjects) {
    List duplicates = myObjects
    .groupBy { it.someAttribute }
    .findAll { it.value.size() > 1 }
    .collect { it.value }
    .flatten()

    assert duplicates.size() != 1
    duplicates
}


The list cannot have the size 1 because if no duplicates are found it must be empty else if there are duplicates it must me at least 2 elements.

Without that check I would do it this way without having to create any new variables:

static List findDuplicateElements(List myObjects) {
    myObjects
    .groupBy { it.someAttribute }
    .findAll { it.value.size() > 1 }
    .collect { it.value }
    .flatten()
}


When using assert, is there any way to avoid saving the result in the duplicates variable and returning it at the end?

Solution

You can use with to do things inline without declaring another variable:

List list = [
  [first: "foo", last: "bar"],
  [first: "baz", last: "qux"],
  [first: "baz", last: "bar"]
]

List findDuplicateElements(myObjects) {
   myObjects
   .groupBy { it.last }
   .findAll { it.value.size() > 1 }
   .collect { it.value }
   .flatten()
   .with {
     assert it.size() != null
     it
   }
}

assert findDuplicateElements(list).size() == 2

Code Snippets

List list = [
  [first: "foo", last: "bar"],
  [first: "baz", last: "qux"],
  [first: "baz", last: "bar"]
]

List findDuplicateElements(myObjects) {
   myObjects
   .groupBy { it.last }
   .findAll { it.value.size() > 1 }
   .collect { it.value }
   .flatten()
   .with {
     assert it.size() != null
     it
   }
}

assert findDuplicateElements(list).size() == 2

Context

StackExchange Code Review Q#57676, answer score: 2

Revisions (0)

No revisions yet.