Enum Potential Limit Method

Is it possible to limit the allowed enumeration values ​​that a method can take?

Say, for example, I have an enumeration like this:

public enum WEEKDAY { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } 

And I will say that I have a method that should only take an internal set of these values:

 //Here dayOfWeek should only be Monday - Friday. public void setWorkDayAlarm(WEEKDAY dayOfWeek) { } 

I know that you can obviously include valid values, and in case of default do nothing. But is there a way (or a template) to determine in the method interface that it only accepts a specific subset of valid enums in Java (5 +)?

+6
source share
4 answers

I don't know what type system can help you. How about something like that?

 public enum DayOfWeek { SUNDAY(false), MONDAY(true), TUESDAY(true), WEDNESDAY(true), THURSDAY(true), FRIDAY(true), SATURDAY(false); private final boolean isWeekday; private DayOfWeek(boolean isWeekday) { this.isWeekday = isWeekday; } public boolean isWeekday() { return isWeekday; } } 

Then check the argument:

 public void setWorkDayAlarm(DayOfWeek dayOfWeek) { if (!dayOfWeek.isWeekday()) throw new IllegalArgumentException("Need weekday, got " + dayOfWeek); // ... } 
+7
source

The language itself makes it impossible to create subsets of the enumeration. First of all, this will lead to the defeat of the purpose of the transfer - to have a certain set of values ​​for a given domain.

What you can do: Define another suitable enumeration for this domain and provide reasonable cross-mappings. To get an idea:

 public enum WORKDAY { MONDAY(WEEKDAY.MONDAY), TUESDAY(WEEKDAY.TUESDAY), WEDNESDAY(WEEKDAY.WEDNESDAY), THURSDAY(WEEKDAY.THURSDAY), FRIDAY(WEEKDAY.FRIDAY); final public WEEKDAY weekday; WORKDAY(WEEKDAY wd){ this.weekday = wd; } static WORKDAY convertWeekday(WEEKDAY weekday){ // in real live use a static EnumMap for(WORKDAY workday: values()) if( workday.weekday == weekday ) return workday; return null; // or an exception } } public void setWorkDayAlarm(WORKDAY workDay){ ... } 

The good thing: the calling conversion method must deal with these values ​​that are not displayable. Your method remains clean.

+3
source

Since the method you have proposed is publicly available, it is permissible to call IllegalArgumentException if the caller has an invalid value. For a private method, you can refuse a debug statement.

+1
source

To do this with a method signature (a type system like @pholser said) is not possible in Plain Old Java. There are some frameworks, such as CDI or alternative programming styles, such as Design By Contract , that can do what you ask.

0
source

Source: https://habr.com/ru/post/899320/


All Articles