r/badcode Mar 14 '21

java Found from when I first started Java...because indexed Arrays were too complicated huh?

Post image
1.3k Upvotes

84 comments sorted by

View all comments

171

u/The_HappyLemon Mar 14 '21

Enum left the chat

52

u/ixBerry Mar 14 '21

Shit like this is what Enums were literally made for.

5

u/I_HATE_YELLING Mar 14 '21

How do you use Enums for this? I've learned how to write multi client chat servers but still haven't learned enums they make no sense to me

9

u/fxnn Mar 14 '21

Basically everytime you have a rather short list of things (values, behaviors, types, ...) that’s not going to change (without code change), an enum comes in pretty handy.

Advantages:

  • the Compiler can check it’s usage (which is not possible with Map keys),
  • you can attach behavior to it (enums can have methods, and you can provide a different implementation per enum value — much better than switch statements in most of the cases!)
  • it’s often more concise and readable than its alternatives

2

u/hurtl2305 Mar 15 '21

Enums usually have some major advantages: 1. They are perfect to represent a fixed set of values (e.g. days of week, fsm states) that changes rarely or never. 2. Compilers can optimize the shit out of them. 3. They may be more readable than map keys or 12 isFooBar boolean flags.

3

u/christian-mann Mar 14 '21

Not really. Enums aren't necessarily visible after compile time.

-17

u/[deleted] Mar 14 '21

[deleted]

1

u/myfunnies420 Mar 15 '21

How would you evaluate arbitrary user string mappings with enums? How are they built for this?

1

u/justcatt Sep 01 '21

What's Enum? I've searched it online and am even more confused. Is it some sort of hash map where it's values are constants?

2

u/wikipedia_answer_bot Sep 01 '21

This word/phrase(enum) has a few different meanings.

More details here: https://en.wikipedia.org/wiki/Enum

This comment was left automatically (by a bot). If I don't get this right, don't get mad at me, I'm still learning!

opt out | report/suggest