Enum Anatomy

Rule 1:Prefer using enum to int constants

why use it?
1.Avoids redundancy:
-The Novice programmer, to use constansts common to class will write in all the classes same values, here enum comes to rescue with it’s huge features.
2.Type safety:
-enums complains at compile time if a TYPE other than expected is passed where as normal class will accept and will throw ClassCastException at run time.
3.loaded with other featues:
enum has a static method values which return all the constants,this feature is not provided in normal class int constants or enum patterns in class
4.more redability
-enums are immutable(no explicit access to constructor to set the values) by nature and provide better redability and verbosity than int constants or int enum patterns in class.

int-enum patterns
string-enum pattern
CONTANT-SPECIFIC BEHAVIOUR
CONSTANT-SPECIFIC DATA

the more is LOC the more boilerplate and more is chances of error.write precise error free code

usecase: sometimes a behaviour is associated with a constant like diet for the specific day of week,CONTANT-SPECIFIC BEHAVIOUR is used to implement it.
–>when there is some commonality in behavious of some but not all Contstants use strategy enum.

Published by

Unknown's avatar

sevanand yadav

software engineer working as web developer having specialization in spring MVC with mysql,hibernate

Leave a comment