A feature I like in Groovy is the ability to import class with aliases. I had forgotten about this feature, so I'm writing about it here to help get it to stick with me a bit.
Take this Spock test class tha has to define a couple several values of a couple types:
import org.company.id.CorporateSymbol
import org.company.id.CorporateName
class CorporationMapperSpec extends Specification {
@Subject
CorporationMapper mapper = new CorporationMapper()
def 'maps corporate symbols to names'() {
expect:
symbolsToNames == mapper.map(symbols)
}
def symbol1 = new CorporateSymbol('KRA')
def symbol2 = new CorporateSymbol('VLY'),
def symbll3 = new CorporateSymbol('KRS'),
def symbolsToNames = [
(symbol1): new CorporateName('Kramerica')
(symbol2): new CorporateName('Vandalay')
(symbol3): new CorporateName('Kruger')
}
}
We can use aliases with the import statements to make the code easier to work with:
import org.company.id.CorporateSymbol as CS
import org.company.id.CorporateName as CN
class CorporationMapperSpec extends Specification {
@Subject
CorporationMapper mapper = new CorporationMapper()
def 'maps corporate symbols to names'() {
expect:
symbolsToNames == mapper.map(symbols)
}
def symbol1 = new CS('KRA')
def symbol2 = new CS('VLY'),
def symbll3 = new CS('KRS'),
def symbolsToNames = [
(symbol1): new CN('Kramerica')
(symbol2): new CN('Vandalay')
(symbol3): new CN('Kruger')
}
}
I would be a little wary about using it in main source, as it does add a little bit of indirection to the readability of the code, but for test source, I think it can definitely help making the code easier to read and work with.