Type safe Enum
โ Why do we need Enum?
Limit field to certain value
- User role can be only
BASIC
,GOLD
,DIAMOND
- ๐๐ป how can we prevent entering
basiiiic
(์คํ) ordiamond
(์๋ฌธ์) orVIP
(์กด์ฌํ์ง ์๋ ๊ฐ)? - ๐ ENUM
โ Type safe enum pattern
- can only use enumerated fields
if only enumerate
BASIC
,GOLD
,DIAMOND
, can only use these three values- ๐๐ป type safe: only can use enumerated fields
- ๐๐ป data consistency
โ Implement enum pattern
- 1๏ธโฃ constant,
static final
enum field 2๏ธโฃ
private
constructor, cannot be created from outside ENUM class- โ๏ธ Example of enum pattern
1
2
3
4
5
6
7
8
9
10
public class ClassGrade {
//same class, but different instance
public static final ClassGrade BASIC = new ClassGrade(); //1๏ธโฃ constant, static final
public static final ClassGrade GOLD = new ClassGrade();
public static final ClassGrade DIAMOND = new ClassGrade();
//2๏ธโฃ private constructor, cannot create from outside this class
private ClassGrade() {
}
}
ClassGrade.BASIC
,ClassGrade.GOLD
,ClassGrade.DIMAOND
is same class- but different instance
โ ENUM
- Java helps the use of
enum pattern
- ๐๐ป type safe: only can use enumerated fields
- ๐๐ป data consistency
1
2
3
public enum Grade {
BASIC, GOLD, DIAMOND
}
- same code as
ClassGrade
- CANNOT be created as instance(
private constructor
) Grade.BASIC
,Grade.GOLD
,Grade.DIMAOND
is same class- but different instance
โ Enum methods
.values()
: get enum values.name()
: get name of value.ordinal()
: get number of value.valueOf()
: set enum value
1
2
3
4
5
6
7
8
9
10
Grade[] values = Grade.values(); //get all values of ENUM
for(Grade value : values){
value.name(); //value ์ด๋ฆ ์ป๊ธฐ
value.ordinal(); //๋ช ๋ฒ์งธ value์ธ์ง return
}
String input = "GOLD";
Grade gold = Grade.valueOf(input); //set ENUM value
โ Enum + Value
want to set different discount value to user
- Basic user: 10% discount
- Gold user: 20% discount
- Diamond user: 30% discount
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public enum Grade {
BASIC(10), GOLD(20), DIAMOND(30);
private final int discountPercent; //add value to ENUM
Grade(int discountPercent) { //private -> need constructor
this.discountPercent = discountPercent;
}
public int getDiscountPercent() { //getter
return discountPercent;
}
}
โ
โ
โ
โ
This post is licensed under CC BY 4.0 by the author.