java
-
이펙티브 자바 : toString개발 나누고 더하기/자바, 스프링 2023. 6. 30. 21:16
toString의 일반 규약에 따르면 '간결하면서 사람이 읽기 쉬운 형태의 유익한 정보'를 반환해야 한다. 아래 PhoneNumber 클래스를 예로 들면 PhoneNumber@adbbd처럼 단순히 클래스_이름@16진수로_표시한_해시코드로 반환하기 보다는 707-867-5309처럼 전화번호를 직접 알려주는 형태가 훨씬 유익하다. 또한 toSting의 규약은 "모든 하위 클래스에서 이 메서드를 재정의하라"고 한다. 새겨들어야 할 조언이다. public final class PhoneNumber { private final int areaCode, prefix, lineNum; //... } toString을 잘 구현한 클래스는 사용하기에 훨씬 즐겁고, 그 클래스를 사용한 시스템은 디버깅하기 쉽다. toStr..
-
이펙티브 자바 - equals & hashcode개발 나누고 더하기/자바, 스프링 2023. 6. 28. 22:29
equals와 hashcode는 루트 클래스인 Object에서 제공하는 오퍼레이션이고 모든 클래스들은 이 두 메서드를 재정의하지 않는 이상 Object에 정의되어 있는대로 쓰게 된다. 실무에서는 주로 식별자로 두 객체가 동일한지 비교하고 가끔 값 객체 비교에 써서 equals를 직접 구현했던 일이 적었다. HashMap, HashSet에 key로 enum이나 Integer, String같은 기본 랩퍼 클래스를 써서 hashcode는 볼일이 거의 없었지만 이 기회에 다시 한번 짚어보는것도 좋을 것 같다. equals는 일반 규약을 지켜 재정의하라 equals 메서드는 재정의하기 쉬워 보이지만 곳곳에 함정이 도사리고 있어서 자칫하면 끔찍한 결과를 초래한다. 문제를 회피하는 가장 쉬운 길은 아예 재정의하지 않..
-
Set에 대하여 2 : 주요 구현체개발 나누고 더하기/자바, 스프링 2023. 6. 25. 22:59
이전 글(https://baby-care-dev.tistory.com/47)에서는 Set의 구조와 메서드에 대해 알아봤다. 메서드 동작은 알았지만 구현체별로 어떻게 내부가 처리되는지도 궁금하다. 예를 들면 TreeSet이나 LinkedHashSet은 어떻게 순서를 보장하는지 등 말이다. 이번에는 구현체별 특징과 공통점/차이점에 대해 알아보자. Set 상속 구조 위 그림에 나온 구현체들 보다 많은 구현 클래스들이 존재하는데, 일단 이정도만 알아도 될 듯 싶다. 모두 공통적으로 AbstractSet이라는 추상 클래스를 상속받고 있다. 이 AbstractSet에서 추상화된 공통점을 파악할 수 있으니 먼저 알아보자. AbstractSet 제공하는 메서드는 equals, hashCode, removeAll이다. ..
-
Set에 대하여 1 : 구조와 주요 메서드개발 나누고 더하기/자바, 스프링 2023. 6. 23. 23:39
Set은 내가 좋아하는 자료구조이다. 중복없이 원소들을 담아놓은 집합체이고, 용도도 중복 검사로 주로 쓰이는 아주 군더더기 없는 구성이라 뭔가 깔끔하다. 그런데 이번에 Set을 org.springframework.cache.annotation.Cacheable에 사용하다 버그를 만들어냈다. 왜 그렇게 생각했는지 모르겠는데 레디스가 Set을 지원하니 key에 사용되는 타입도 Set을 지원할 줄 알았다. 하지만 Key는 정직하게 스트링 값으로만 비교를 했고, 의도치 않게 여러가지 버전의 캐시를 만들어 내고 말았다. 대략 아래 코드와 같았다. List로 할까 고민했었는데, 좀 안일했었다. 로컬과 개발(인스턴스 2대) 환경에서 테스트해도 문제가 없었지만 운영환경에서 몇십대(정확한 대수는 공개하기 민감하므로^^)..
-
이모지와 유니코드 그리고 자바개발 나누고 더하기/자바, 스프링 2023. 4. 22. 00:09
발단 2021년 어느날 회사 서비스의 DB 컬레이션을 utf8mb4로 수정하였다. 회사 내 다른 서비스와 상품 연동을 하는데, 이 채널로부터 4bytes 이모지가 포함된 상품 데이터를 받아 해당 상품 페이지의 이모지가 다 깨져 나왔기 때문이다. 우리는 DB 컬레이션만 수정하면 되는데 문제는 우리와 상품 연동을 하는 또 제 3의 서비스에서 이모지 허용이 안되는 것이 문제였다. 이모지를 걸러서 전송해야 하는데 2가지 방향으로 문제를 풀 수 있다. 화이트 리스트를 만들어 이 안에 포함된 문자만 허용하거나 블랙 리스트를 만들어 그 안에 든 문자들을 제거하는 것이다. 그 당시 이 문제를 담당했던 개발자는 전자를 택하여 아래와 같은 코드가 나왔다. public class EmojiUtil { private stat..