-
이넘(enum)spring.project.log 2022. 3. 17. 15:38
ref
https://www.w3schools.com/java/java_enums.asp
Java Enums
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
이넘은 크게 두 가지 뜻을 가지고 있다.
1. 열거형
2. 상수들을 묶어놓은 것을 나타내는 클래스An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).
두 가지 의미를 연결하면 "상수"를 열거한 클래스라는 추측은 쉽게 가능하다. 하지만 의문점이 생긴다. 왜 상수를 특정한 클래스 안에 넣어서 그룹화한 걸까?
우선 이넘에 대해 뭐라고 설명하는지 더 찾아보았다.
고정된 상수 집합을 나타내려면 항상 이넘을 사용해야 한다. 여기에는 태양계의 행성 같이, 컴파일 타임에 모든 값을 알 수 있는 데이터 집합 (예: 메뉴의 선택 사항, 커맨드 라인 플래그 등)과 같은 자연 열거 유형이 포함된다.
You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.
그러니까 여기서 상수에 대한 이해가 동반되어야 공식문서의
참맛을알 수 있다.내가 이해하기로는 상수는 이미 값을 할당하고 재할당할 수 없게 고정된 값(변하지 않는 값 ex : 파이 3.14)이므로 자바가 바이트코드로 변환되는 컴파일 타임에서는 이미 값이 고정되어 있기 때문에 런타임에 값이 변하지 않는다. 따라서 이런 경우에(이미 값이 고정된 경우) 상수들을 모아놓은 이넘이라는 클래스를 쓰는 것이다.
추가) 일단 저 예시(커맨드 라인 플래그나 메뉴의 선택)은 이 시점에서는 이해가 가지 않는다.
그렇다면 변하지 않게 값을 고정해두는 것의 장점-즉 상수를 쓰는 이유-을 알아야할 것 같은데 일단 이거 토끼굴 각이니까 여기서 질문을 해보아야겠다. 워낙에 상수 나오면 힙 스택 상수풀 (...)로 이어지는 개미지옥 (하지만 의외로 지금 다시 보면 지옥같지는 않을지도?)
ref
https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
Enum Types (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated
docs.oracle.com
질문을 했는데 나의 추측이 틀렸다 ! 상수랑은 관련이 없고, 정해진 값을 보장하고 타입을 강제하고 싶을 때 쓴다. (실무적으로 다른 이유가 있지만 일단은 여기까지)
1) 문자열 하드코딩을 쓰지 않으려고
예시) 카페라떼 가 들어가야하는데 오타가 났다면(카페라때) cannot defined ...가 뜨기 때문에 디버깅하기가 어렵다..
2) 숫자 하드코딩을 쓰지 않으려고
예시) status code 2000ok 브라우저입장에서 그런거 없는데? 라고 당황할 수 있음
이건 타입의 문제다 어떤 함수는 정해진 값들만 받아야 하는데 모든숫자가 다 들어올 수 있는게 아님 200, 403 http status code를 맘대로 매개변수를 enum으로 받으면 된다~
정해진값을 넣고, 타입을 강제하고 검사하기 위해서는 자바에선 이넘, 타입스크립트에서는 유니언 타입을 쓴다고 한다.타입스크립트에도 enum의 존재가 없는 것은 아니지만, 유니언을 많이 쓴다고 한다 (왜?)워낙에는 DB에서 용량을 줄이기 위해서 이넘을 썼었다고 한다! 왜냐하면 숫자와 문자열은 저장 용량 수준이 크게 차이나기 때문이다 ~ 하지만 요즘은 인덱싱을 잘 걸어주어서 DB가 데이터를 찾는 시간을 줄이는 방법이 많이 생겨서 용량을 줄이기 위한 이유로는 잘 쓰지 않는 편이라고 한다~추가
타입스크립트의 union 타입
ref
https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types
Documentation - Everyday Types
The language primitives.
www.typescriptlang.org
타입스크립트에서의 union 타입 정의하기
function printId(id: number | string) { console.log("Your ID is: " + id); } // OK printId(101); // OK printId("202"); // Error printId({ myID: 22342 }); Argument of type '{ myID: number; }' is not assignable to parameter of type 'string | number'.
printId("202")를 보면 {myID:22342} 처럼 객체이기 때문에 스트링이나 넘버타입이 아니기 때문에 에러가 뜬다. 이렇게 타입을 강제로 지정해주었을 때 장점은
코드를 작성하다가 객체로 리턴하게 하는 실수를 했을 때 유니언이 타입을 걸러주기 때문에 실수할 가능성이 줄어든다
하지만 타입스크립트 공식문서에서는 다음과 같은 문제를 제기한다.
유니언의 멤버로 타입을 제공하면 되기 때문에 vlaue와 타입을 매칭하는 건 쉽다. 하지만 모든 멤버에 적용이 되기 때문에 아래의 예제처럼 toUpperCase()같은 메서드는 넘버타입으로 실행할 수 없다.
Working with Union Types
It’s easy to provide a value matching a union type - simply provide a type matching any of the union’s members. If you have a value of a union type, how do you work with it?
TypeScript will only allow an operation if it is valid for every member of the union. For example, if you have the union string | number, you can’t use methods that are only available on string:
function printId(id: number | string) { console.log(id.toUpperCase()); Property 'toUpperCase' does not exist on type 'string | number'. Property 'toUpperCase' does not exist on type 'number'.Property 'toUpperCase' does not exist on type 'string | number'. Property 'toUpperCase' does not exist on type 'number'. }
아니 여기 영어를 해석못하지만 코드는 이해가 간다...
The solution is to narrow the union with code, the same as you would in JavaScript without type annotations. Narrowing occurs when TypeScript can deduce a more specific type for a value based on the structure of the code.
For example, TypeScript knows that only a string value will have a typeof value "string":
function printId(id: number | string) { if (typeof id === "string") { // In this branch, id is of type 'string' console.log(id.toUpperCase()); } else { // Here, id is of type 'number' console.log(id); } }
실제 활용 사례
https://jojoldu.tistory.com/137
Enum 활용사례 3가지
안녕하세요? 이번 시간엔 enum 활용사례를 3가지정도 소개하려고 합니다. 모든 코드는 Github에 있기 때문에 함께 보시면 더 이해하기 쉬우실 것 같습니다. (공부한 내용을 정리하는 Github와 세미
jojoldu.tistory.com
https://techblog.woowahan.com/2527/
Java Enum 활용기 | 우아한형제들 기술블로그
{{item.name}} 안녕하세요? 우아한 형제들에서 결제/정산 시스템을 개발하고 있는 이동욱입니다. 이번 사내 블로그 포스팅 주제로 저는 Java Enum 활용 경험을 선택하였습니다. 이전에 개인 블로그에 E
techblog.woowahan.com
'spring.project.log' 카테고리의 다른 글
[JAVA] 접근제어자, getter/setter (0) 2022.03.26 오버라이딩(overriding)과 오버로딩(overloading) (0) 2022.03.18 인터페이스(interface) (0) 2022.03.17 추상클래스(abstract class) (0) 2022.03.17 spring 첫회의 (0) 2022.03.04