Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How bad is it considered to create enums with large enough amount of enumerators and abstract methods [closed]

Tags:

java

enums

I have the following enum:

public enum RuleItem {
    MORE_THAN(1) {
        @Override
        public String getStringRepresentation() {
            return getRuleStringRepresentation("rulesName.moreThan");
        }
    },
    LESS_THAN(2) {
        @Override
        public String getStringRepresentation() {
            return getRuleStringRepresentation("rulesName.lessThan");
        }
    },
    MORE_OR_EQUAL(3) {
        @Override
        public String getStringRepresentation() {
            return getRuleStringRepresentation("rulesName.moreOrEqual");
        }
    },

    //...

    INTERVAL_WITH_BOUNDS_INCLUDED(27) {
        @Override
        public String getStringRepresentation() {
            return getRuleStringRepresentation("rulesName.intervalWithBounds");
        }
    };
    protected String getRuleStringRepresentation(String resourceName) {
        Locale locale = FacesContext.getCurrentInstance().getViewRoot()
            .getLocale();
        String resourceString;
        try {
            ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_NAME,
                locale);
            resourceString = bundle.getString(resourceName);
        } catch (MissingResourceException e) {
            return null;
        }

        return resourceString;
    }

    public abstract String getStringRepresentation();
}

I want to add three more abstract methods. Is it considered good the enum contains large amount of public methods? Maybe I should have created just a class in that case?

like image 988
St.Antario Avatar asked Dec 03 '22 17:12

St.Antario


1 Answers

Why not simply use a constructor, something like:

public enum RuleItem {
    MORE_THAN(1, "rulesName.moreThan"),
    LESS_THAN(2, "rulesName.lessThan"),
    MORE_OR_EQUAL(3, "rulesName.moreOrEqual");

    private int value;
    private String representation;

    private RuleItem(int value, String representation) {
        this.value = value;
        this.representation = representation;
    }

    public String getStringRepresentation() {
         return representation;
    }
}

You can then add as many arguments and as methods as you'd like, but without having the override it personally for each value (simply pass it in the constructor).

like image 81
Ori Lentz Avatar answered Mar 23 '23 01:03

Ori Lentz