15 + 11 Mistakes Every Java Developer MUST avoid TODAY
Medium
1. Nulls와 Optionals
Bad Practice: 메서드에서 바로 null을 리턴하는 건 NPE를 유발할 수 있습니다.
public String getString() {
return null;
}
Good Practice: null에 대한 명확한 핸들링과 에러 방지를 위해 Optional을 사용합니다.
public Optional<String> getString() {
return Optional.empty();
}
2. String.valueOf()로 String 변환
Bad Practice: + 연산자를 사용해 문자열을 합칩니다.
double d = 3.14525;
String s = "" + d;
Good Practice: 내장 메서드를 활용합니다.
double d = 3.14245;
String s = String.valueOf(d);
3. array를 복사할 때 Arrays.copyOf()
Bad Practice: 정석적으로 array를 복사합니다.
int[] sourceArray = {1,2,3,4,5};
int[] targetArray = new int[sourceArray.length];
for (int i = 0; i< sourceArray.length; i++) {
targetArray[i] = sourceArray[i];
}
Good Practice: Arrays.copyOf() 메서드를 사용합니다.
int[] sourceArray = {1,2,3,4,5};
int[] targetArray = Arrays.copyOf(sourceArray, sourceArray.length);
4. 컬렉션이 비어있는지 체크하기 위해 isEmpty()
Bad Practice: length()나 size()로 string이나 컬렉션이 비어있는지 체크합니다.
String text = "Hello, World!";
if(text.length() == 0) {
// Do something
}
Good Practice: isEmpty()로 string이나 컬렉션이 비어있는지 체크합니다.
String text = "Hello, World!";
if(text.isEmpty()) {
// Do something
}
5. Concurrent Modification Exception 방지
Bad Practice: 리스트를 순회하고 있는 동안 요소를 제거하여 ConcurrentModificationException을 일으킵니다.
List<String> words = new ArrayList<>();
words.add("A");
words.add("B");
words.add("C");
for(String word : words) {
if (word.equals("A")) {
words.remove(word);
}
}
Good Practice: iterator remove 메서드나 removeIf() 메서드를 사용합니다.
List<String> words = new ArrayList<>();
words.add("A");
words.add("B");
words.add("C");
Iterator<String> iterator = words.iterator();
while (iterator.hasNext()) {
String word = iterator.next();
if (word.equals("A")) {
iterator.remove(); // Use iterator's remove method to safely remove elements
}
}
System.out.println(words); // Output: [B, C]
6. 정규표현식 사전 컴파일
Bad Practice: 런타임 시에 정규표현식을 컴파일합니다.
String text = "Hello, World!";
if(text.matches("Hello.*")) {
System.out.println("Matches!");
}
String replaced = text.replaceAll("\\s", "");
Good Practice: 정규표현식을 사전컴파일하고 재사용합니다.
final Pattern PATTERN1 = Pattern.compile("Hello.*");
final Pattern PATTERN2 = Pattern.compile("\\s");
String text = "Hello, World!";
if(PATTERN1.matcher(text).matches()) {
System.out.println("Matches!");
}
String replaced = PATTERN2.matcher(text).replaceAll("");
번역: [https://ducktopia.tistory.com/124]
원문
다음 내용이 궁금하다면?
이미 회원이신가요?
2024년 5월 17일 오전 10:42
나는 가끔 조합형 한글의 아름다움에 대해 생각한다.
그 아름다움은 단순히 예쁜 글꼴이나 정갈한 종이 위의 자소 배열에서 끝나지 않는다. 진짜 매력은, 정밀한 정보 구조와 이산 수학적 규칙성 속에 숨어 있다.
2000년 초반부터 온톨로지 연구를 해왔고, 관심을 갖고 있는 사람으로서 GraphRAG 에 대해 갖고 있는 생각을 적어봤습니다.
... 더 보기직장인으로서 10년 정도 일하게 되면 피할 수 없는 순간이 바로 조직에서 리더의 역할을 받게 되는 인사발령이다. 팀원이었을 때는 내게 주어진 업무를 내가 가진 능력과 주변 동료들의 도움으로 해결하고, 그에 합당한 평가와 보상을 기다리며, 나쁘지 않는 리워드와 내 위치에 안도하며 또 새해를 맞이하고 하루하루를 버텨나가는 과정에 큰 어려움이 없다.
... 더 보기안
... 더 보기