Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2006

Tip: Looking for answers? Try searching our database.

How to prevent code repetition with enums?

Thread view: 
daniel_nordlund_1982@hotmail.com - 17 Nov 2006 12:03 GMT
Hello. I was wondering if there is a better way to write the below
code. I have several enums, where each enum is for an option type and
each option has a short 1-3 letter string used when I need to identify
the option from a string. The code for each option type is identical
and I'd prefer to not repeat it over and over again.

static enum YesNoOption {
 YES("yes"), NO("no");
 private final String str;
 private YesNoOption(String str) { this.str = str; }
 public String getOptionString() { return str; }
 public static YesNoOption getOption(String str) {
   for(YesNoOption o: YesNoOption.values())
     if(o.str.equals(str))
       return o;
   return null;
 }
}

static enum ColorOption {
 BLUE("b"), RED("r"), GREEN("g"), MAGENTA("m"), YELLOW("y");
 private final String str;
 private ColorOption(String str) { this.str = str; }
 public String getOptionString() { return str; }
 public static ColorOption getOption(String str) {
   for(ColorOption o: ColorOption.values())
     if(o.str.equals(str))
       return o;
   return null;
 }
}

...

-------------

YesNoOption yesno = YesNoOption.getOption("no");
ColorOption color = ColorOption.getOption("g");

if(color == ColorOption.GREEN) {
 ...
}

Daniel
Chris Uppal - 17 Nov 2006 13:31 GMT
> Hello. I was wondering if there is a better way to write the below
> code. I have several enums, where each enum is for an option type and
> each option has a short 1-3 letter string used when I need to identify
> the option from a string. The code for each option type is identical
> and I'd prefer to not repeat it over and over again.

As far as I know there is no way to remove the repetition.  So, if it bothers
you particularly (and it would bother me ;-) I suggest that you generate the
enum classes automatically.

Exactly how you do that depends on what programming language your favour for
text manipulation, and on what restrictions (if any) your build environment
imposes.

   -- chris
Piotr Kobzda - 17 Nov 2006 14:42 GMT
>> Hello. I was wondering if there is a better way to write the below
>> code. I have several enums, where each enum is for an option type and
[quoted text clipped - 5 lines]
> you particularly (and it would bother me ;-) I suggest that you generate the
> enum classes automatically.

Yes.  That's the option.

But a little improvement is also possible here with a single
implementation of the lookup logic, like in the following example:

public class Options {

    public interface Option {
        String getOptionString();
    }

    public static enum YesNoOption implements Option {
        YES("yes"), NO("no");
        private final String str;
        private YesNoOption(String str) { this.str = str; }
        public String getOptionString() { return str; }
        public static YesNoOption getOption(String str) {
            return forString(YesNoOption.class, str);
        }
    }

    // ... other options ...

    public static <T extends Enum<T> & Option> T forString(
            Class<T> optionType, String str) {
        for(T o : optionType.getEnumConstants())
            if(o.getOptionString().equals(str))
               return o;
        return null;
    }

}

piotr
EJP - 18 Nov 2006 00:40 GMT
> public static YesNoOption getOption(String str) {
    for(YesNoOption o: YesNoOption.values())
      if(o.str.equals(str))
        return o;
    return null;
  }     }

This method is redundant. Enum has a static valueOf() method with,
curiously enough, the same parameters and return type as the above. It
throws IllegalArgumentException instead of returning null.
daniel_nordlund_1982@hotmail.com - 18 Nov 2006 10:15 GMT
EJP skrev:
> > public static YesNoOption getOption(String str) {
>      for(YesNoOption o: YesNoOption.values())
[quoted text clipped - 6 lines]
> curiously enough, the same parameters and return type as the above. It
> throws IllegalArgumentException instead of returning null.

The problem is that with valueOf I have to use the full enum
identifier:

ColorOption color = ColorOption.valueOf("GREEN");

But I need this method to look up an option given it's abbreviation:

ColorOption color = ColorOption.getOption("g");

Thank you Piotr for your improved code!

Daniel
仁者无敌 - 18 Nov 2006 09:37 GMT
> > daniel_nordlund_1...@hotmail.com wrote:
>
[quoted text clipped - 35 lines]
>                 return o;
>          return null;
     Very strong template code......
     hard to understand,could you explain what the template trys to
describe by the way?
>      }
>
> }piotr


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.