분류 전체보기
-
item 67 최적화는 신중히 하라책/이펙티브 자바 2022. 4. 22. 09:54
ITEM 67 최적화는 신중히 하라 최적화 격언 세가지 맹목적인 어리석음을 포함해 그 어떤 핑계보다 효율성이라는 이름 아래 행해진 컴퓨팅 죄악이 더 많다(심지어 효율을 높이지도 못하면서) 윌리엄 울프 전체의 97% 정도인 자그마한 효율성은 모두 잊자. 섣부른 최적화가 만악의 근원이다 도널드 크누스 최적화를 할 때는 다음 두 규칙을 따르라 첫번째 하지마라 두번째 전문가 한정 아직 하지마라. 다시말해, 완전히 명백하고 최적화되지 않은 해법을 찾을 때까지는 하지 마라 M. A. 잭슨 이 격언들은 자바가 탄생하기 20년 전에 나왔으며 최적화의 어두운 진실을 이야기한다 최적화는 좋은 결과보다 안좋은 결과가 나타나기 쉽다 잘못하면 빠르지도 않고 제대로 동작하지도 않으면서 수정이 어려워진다 성능 때문에 견고한 구조를..
-
item 66 네이티브 메서드는 신중히 사용하라책/이펙티브 자바 2022. 4. 21. 17:54
ITEM 66 네이티브 메서드는 신중히 사용하라 자바 네이티브 인터페이스(Java Native Interface, JNI) 자바 프로그램이 네이티브 메서드를 호출하는 기능이다 네이티브 메서드: C, C++ 같은 네이티브 프로그래밍 언어로 작성한 메서드 전통적으로 네이티브 메서드는 아래 3가지 경우에 주로 사용된다 레지스트리 같은 플랫폼 특화 기능을 사용한다 네이티브 코드로 작성된 기존 라이브러리를 사용한다 레거시 데이터를 사용하는 레거시 라이브러리가 그 예다 성능 개선을 목적으로 성능에 결정적인 영향을 주는 영역만 따로 네이티브 언어로 작성한다 플랫폼 특화 기능을 활용하려면 네이티브 메서드를 사용해야 하지만 자바가 성숙해지며(OS 같은) 하부 플랫폼의 기능을 흡수하고 있다 따라서 네이티브 메서드를 사용할..
-
item 65 리플렉션보다는 인터페이스를 사용하라책/이펙티브 자바 2022. 4. 21. 17:54
ITEM 65 리플렉션보다는 인터페이스를 사용하라 리플렉션을 쓰면 프로그램에서 임의의 클래스에 접근할 수 있다(java.lang.reflect) Class 객체가 주어지면 그 클래스의 생성자, 메서드, 필드에 해당하는 Constructor, Method, Field 인스턴스를 가져올 수 있다 가져온 인스턴스들로는 그 클래스의 멤버 이름, 필드 타입, 메서드 시그니처 등을 가져 올 수도 있다 Constructor, Method, Field 인스턴스를 이용해 각각에 연결된 실제 생성자, 메서드, 필드를 조작할 수도 있다 이 인스턴스를 이용해서 해당 클래스의 인스턴스를 생성하거나 메서드를 호출하거나 필드에 접근 가능하다는 말이다 ex) Method.invoke는 어떤 클래스의 어떤 객체가 가진 어떤 메서드라도..
-
item 64 객체는 인터페이스를 사용해 참조하라책/이펙티브 자바 2022. 4. 21. 17:54
ITEM 64 객체는 인터페이스를 사용해 참조하라 적합한 인터페이스만 있다면 매개변수뿐 아니라 반환값, 변수, 필드를 전부 인터페이스 타입으로 선언하라 객체의 실제 클래스를 사용해야 할 상황은 오직 생성자로 생성할 때 뿐이다 Set 인터페이스를 구현한 LinkedHashSet 변수를 선언하는 올바른 모습 //인터페이스를 타입으로 선언한 좋은 예 Set sonSet = new LinkedHashSet(); //클래스를 타입으로 사용한 나쁜 예 LinkedHashSet sonSet = new LinkedHashSet(); 인터페이스를 타입으로 사용하는 습관을 길러두면 프로그램이 훨씬 유연해질것이다 구현 클래스를 교체하는 상황이 발생하면 그저 새 클래스의 생성자나 다른 정적 팩터리를 호출해주기만 하면된다첫번째..
-
item 63 문자열 연결은 느리니 주의하라책/이펙티브 자바 2022. 4. 21. 17:53
ITEM 63 문자열 연결은 느리니 주의하라 문자열 연결 연산자(+)는 여러 문자열을 하나로 합칠때 많이 사용한다 한 줄 짜리 출력값, 작고 크기가 고정된 객체의 문자열 표현을 만드는 경우는 괜찮다 하지만 본격적으로 사용하면 성능 저하를 감내하기가 어렵다 문자열 연결 연산자로 문자열 n개를 잇는 시간은 n²에 비례한다 문자열은 불변이라 두 문자열을 연결하면 양쪽의 내용을 모두 복사하니 성능 저하는 필연적이다 청구서의 품목(item)을 전부 하나의 문자열로 연결하는 코드 문자열 연결을 잘못 사용한 예 public String statement() { String result = ""; for (int i = 0; i < numItems(); i++) { result += lineForItem(i); //문..
-
item 62 다른 타입이 적절하다면 문자열 사용을 피하라책/이펙티브 자바 2022. 4. 21. 17:53
ITEM 62 다른 타입이 적절하다면 문자열 사용을 피하라 String은 텍스를 표현하도록 설계되었고 설계 의도대로 아주 잘 동작하지만 워낙 흔하고 자바가 잘 지원해주어 원래의 의도와 다른용도로 쓰이는 경우가 많다 문자열을 쓰지 않아야 하는 경우 문자열은 다른 값 타입을 대신하기에 적합하지 않다 많은 경우 파일, 네트워크, 키보드 입력으로부터 데이터를 받을 때 문자열을 사용하는 경우가 많지만 입력받을 데이터가 진짜 문자열인 경우에만 쓰는게 좋다 받은 데이터가 수치형이면 int, float, BigInteger 등 적당한 수치형 타입으로 변환해야 한다 예/아니오 같은 질문의 답이라면 적절한 열거 타입이나 boolean으로 변환해야 한다 일반화해서 이야기하면 기본 타입이든 참조 타입이든 적절한 값 타입이 있..
-
item 61 박싱된 기본 타입보다는 기본 타입을 사용하라책/이펙티브 자바 2022. 4. 21. 17:52
ITEM 61 박싱된 기본 타입보다는 기본 타입을 사용하라 자바의 데이터 타입은 크게 두 가지로 나눌 수 있다 기본타입 int, double, boolean 참조타입 String, List 각각의 기본 타입에는 대응하는 참조타입이 하나씩 있으며 이를 박싱된 기본 타입이라고 한다 ex) int, double, boolean 에 대응하는 박싱된 기본타입은 Integer, Double, Boolean이다 오토박싱과 오토언박싱 덕분에 두 타입을 크게 구분하지 않고 사용 가능 하지만 그렇다고 차이가 없는 것은 아니다 둘 상시에는 분명한 차이가 있으니 어떤 타입을 사용할건지는 중요하며 신중하게 선택 해야 한다 기본 타입과 박싱된 기본 타입은 크게 세가지 차이가 있다 기본 타입은 값만 가지고 있지만 박싱된 기본 타입..
-
item 60 정확한 답이 필요하다면 float와 double은 피하라책/이펙티브 자바 2022. 4. 21. 17:52
ITEM 60 정확한 답이 필요하다면 float와 double은 피하라 float와 double 타입은 과학과 공학 계산용으로 설계되었다 이진 부동소수점 연산에 쓰이며, 넓은 범위의 수를 빠르게 정밀한 근사치로 계산하도록 세심하게 설계 되었다 정확한 결과가 필요한 경우에는 사용하면 안되며 float와 double 타입은 특히 금융 관련 계산과는 맞지 않는다 0.1 혹은 10의 음의 거듭 제곱수를 표현할 수 없기 때문이다 주머니에 1.03달러가 있었는데 그중 42센트를 쓰면 남은 돈은 얼마인가? 어설프게 작성한 코드 System.out.println(1.03 - 0.42); 안타깝게도 결과는 0.60......1 주머니에 1달러가 있었는데 10센트짜리 사탕 9개를 샀으면 얼마가 남았을까 System.out..
-
item 59 라이브러리를 익히고 사용하라책/이펙티브 자바 2022. 4. 21. 17:52
ITEM 59 라이브러리를 익히고 사용하라 기존에 제공하는 표준 라이브러리의 기능 대신 직접 구현하는건 추천하지 않는다 표준 라이브러리를 사용하면 아래와 같은 이점이 있다 표준 라이브러리를 사용하면 그 코드를 작성한 전문가의 지식과 여러분보다 앞서 사용한 다른 개발자들의 경험을 활용할 수 있다 핵심적인 일과 크게 관련 없는 문제를 해결하느라 시간을 허비하지 않아도 된다 따로 노력하지 않아도 성능이 지속해서 계선된다 업계 표준 벤치마크를 사용해 성능을 확인하기 때문에 표준 라이브러리 제작자들은 더 나은 방법을 꾸준히 모색한다 기능이 점점 많아진다 라이브러리에 부족한 부분이 있다면 개발자 커뮤니티에 이야기가 나오고 논의 한 후 다음 릴리즈에 추가되는 경우도 많다 내가 작성한 코드가 다른 사람들이 보기에도 낯..
-
item 58 전통적인 for 문보다는 for-each문을 사용하라책/이펙티브 자바 2022. 4. 21. 17:51
ITEM 58 전통적인 for 문보다는 for-each문을 사용하라 향상된 for문(enhanced for statement) 정식 명칭은 향상된 for문 이지만 for-each문 이라고 부른다 반복자와 인덱스 변수를 사용하지 않으니 코드가 깔끔하고 오류가 날 일도 없다 하나의 관용구로 컬렉션과 배열을 모두 처리 가능하여 어떤 컨테이너를 다루는지 신경쓰지 않아도 된다 for (Element e : elements) { ... // e로 무언가를 한다 } : 은 "안의(in)"라고 읽으면 되며 위 코드는 "elements 안의 각 원소 e에 대해"라고 읽는다 반복 대상이 컬렉션이든 배열이든 for-each문을 사용해도 속도는 그대로다 for-each문이 만들어내는 코드는 사람이 손으로 최적화한 것과 사실상..