Currently, there are only 3 possible publishers. I might want to add some more in the future:

interface NewsArticle {
    enum Publisher { NYPost, ChiTribune, LATimes }

    Publisher getPublisher();
}

I like the rigidity of using enum, but when might I get tripped-up if I treat the publisher as an enum instead of a String?

有帮助吗?

解决方案

There shouldn't generally be a need to rebuild an application when new data is introduced. If there's no need to define and implement any publisher related logic every time a new Publisher is introduced, then enum is a wrong choice.

Where exactly in your application you need to refer to a certain Publisher? Do you have some logic that's bound to the Publisher in your application? Like

if (article.getPublisher().equals(Publisher.NYPost) {
   doSomethingNyPostRelated();
}

Do you have any such references? If you don't have any, then you shouldn't have a hard coded set of Publishers, as an enum or otherwise.

I like the rigidity of using enum, but when might I get tripped-up if I treat the publisher as an enum instead of a String?

How about a Publisher class that's not an enum?

public class Publisher {
    private final int id;
    private final String name; // perhaps?
    ...
}

That would give you more rigidity than a String without being limited to only some hard coded predefined publishers. First, you would be able to control the creation, the validity and the use of Publishers. Second you would have the type safety: you wouldn't be able to pass or return a random String as a Publisher. Third, you could read a predefined set of Publishers from a database or from a configuration file, whatever is preferred:

public class PublisherRepository {
    public List<Publisher> getAllPublishers() {
         // read publishers from db or config file
    }
}

Of course you could even have your PublisherRepository return a hard coded list of Publishers at first. Changing a properly structured hard coded solution wouldn't be as difficult as replacing an enum.

其他提示

A possible hack would be to use a "dynamic enum", which is non-standard. You read possible values from a file a load time. So it's "only" editing a text file, not recompiling. e.g.

https://dzone.com/articles/enum-tricks-dynamic-enums

I have no experience with these things so caveat emptor. Probably not worth the effort but YMMV.

As per the comment from Robert Harvey:

That shouldn't be an enum. Adding a publisher requires you to recompile the application.

that is all I need to know.

There are only two ways:

One is to use external source such as files or databases and the second is recompiling.

It makes no difference if it is a String or Enum if the options reside in the code.

许可以下: CC-BY-SA归因
scroll top