Hello. In the design of the application often come across static elements, for example, bottom navigation buttons that are responsible for changing the fragment, lists of categories, checkboxes, sorting types, social network buttons, etc. Everywhere I use enum. For example, I create an enum for the buttons of the lower navigation and I β€œhard-core” classes of fragments, for the buttons of the social. networks - enums with their links, titles, links to pictures in R.drawable. For sorting (say from the database) - I also make specific instances for ORM of the SortedBy type right in the fields. In general, for all static data I use Enum. Literally the whole project is already teeming with them.

I believe that enums are useful in case of real similarities. But now, more and more extensions appear, for example, when switching to a specific fragment, it is required to throw information about it into the analytics, and for one specific fragment. In general, now all this beauty turns into ugliness. For those fragments to which the analyst is not using, I attribute null in the fields and then do checks on them.

Tell me, is it good to use enums? Now it's better to rewrite everything (for what?) Or continue to write crutches?

When do you really need to use them? And is it necessary at all?

    1 answer 1

    Enum should be used when you need a) a finite, b) a predetermined, c) an adequately named set of d) unique values.

    For example, a traffic light has only three signals (exaggerating).

     public enum TrafficLight{ RED, YELLOW, GREEN; } 

    Now, setting the current burning section, you (your colleague) will be able to use only this specific set of colors and will not be able to set, for example TrafficLight.BLUE

     Lights lights = new Lights(); lights.current = TrafficLight.BLUE; // Ошибка ΠΌΠΎΠΌΠ΅Π½Ρ‚Π° компиляции // lights.current ΠΈΠΌΠ΅Π΅Ρ‚ Ρ‚ΠΈΠΏ TrafficLight 

    Enum are good for creating short dictionaries (for example, statuses of something) or as flags (if you do not intend to combine them). To shove them everywhere and for any reason, of course, is not necessary.

    In addition, enum far from free. Please note that there are practically no Android SDKs, and numeric constants are used instead. Read why it was done like this.

    Just do not rush to destroy enum s in favor of numerical constants - this is not always justified. :) For example, if we replace the traffic light color class following Google’s example with numbers:

     public class TrafficLight{ public static final Integer RED = 1; public static final Integer YELLOW = 2; public static final Integer GREEN = 3; } 

    That will not be any protection from such a jamb:

     Lights lights = new Lights(); lights.current = 4; // Π₯Ρ€Π΅Π½Π½Π°ΠΉΠ΄ΠΈΠ±Π΅Π»ΡŒΠ½Π°Ρ ошибка Π² Ρ€Π°Π½Ρ‚Π°ΠΉΠΌΠ΅ // lights.current ΠΈΠΌΠ΅Π΅Ρ‚ Ρ‚ΠΈΠΏ Integer - Π½ΠΈ ΠΎ Ρ‡Π΅ΠΌ Π½Π΅ Π³ΠΎΠ²ΠΎΡ€ΠΈΡ‚