Post

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(์˜คํƒ€) or diamond(์†Œ๋ฌธ์ž) or VIP(์กด์žฌํ•˜์ง€ ์•Š๋Š” ๊ฐ’)?
  • ๐Ÿ’Š 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.