grantmcconnaughey
grantmcconnaughey

Reputation: 10689

Creating DRY enums

I would like to share similar functionality between a few different enums using Groovy 2.1.9. The enums are all used to generate XML, so I have given them a property called xmlRepresentation. Here are two of the enums:

enum Location {
    CollegeCampus('College Campus'), HighSchool('High School'), Online('Online')

    Location(String xmlRep) {
        this.xmlRepresentation = xmlRep
    }

    String toString() {
        xmlRepresentation
    }

    String xmlRepresentation
}


enum InstructorType {
    CollegeFaculty('College Faculty'), HighSchoolFaculty('High School Faculty')

    InstructorType(String xmlRep) {
        this.xmlRepresentation = xmlRep
    }

    String toString() {
        xmlRepresentation
    }

    String xmlRepresentation
}

As you can see, I have to declare the xmlRepresentation property, toString method, and constructor in both of these enums. I would like to share those properties/methods, but I don't think I can inherit with enums. I have tried using a mixin without any luck:

class XmlRepresentable {

    String xmlRepresentation

    XmlRepresentable(String xmlRepresentation) {
        this.xmlRepresentation = xmlRepresentation
    }

    String toString() {
        this.xmlRepresentation
    }
}


@Mixin(XmlRepresentable)
enum Location {
    CollegeCampus('College Campus'), HighSchool('High School'), Online('Online')
}

This yielded the error Could not find matching constructor for: com.company.DeliveryFormat.

Does anyone know how I can share this functionality and keep my code DRY? Thank you!

Upvotes: 2

Views: 414

Answers (1)

dmahapatro
dmahapatro

Reputation: 50245

Here is a little motivation to move to Groovy 2.3.0 and above. :) Some amount of DRYness using trait

trait Base {
    final String xmlRepresentation

    void setup(String xmlRep) {
        this.xmlRepresentation = xmlRep
    }

    String toString() {
        xmlRepresentation
    }

    String getValue() {
        xmlRepresentation
    }
} 

enum Location implements Base {
    CollegeCampus('College Campus'), HighSchool('High School'), Online('Online')
    Location(String xmlRep) { setup xmlRep }
}

enum InstructorType implements Base {
    CollegeFaculty('College Faculty'), HighSchoolFaculty('High School Faculty')
    InstructorType(String xmlRep) { setup xmlRep }
}

assert Location.HighSchool in Location
assert Location.Online.value == 'Online'
assert InstructorType.CollegeFaculty in InstructorType

There is nothing much I think can be done with what you have right now AFAIK.

Upvotes: 5

Related Questions