🕊️ [Medium] 자바 개발자가 피해야 하는 11가지 실수 (1)

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]

원문

15 + 11 Mistakes Every Java Developer MUST avoid TODAY

Medium

15 + 11 Mistakes Every Java Developer MUST avoid TODAY

다음 내용이 궁금하다면?

또는

이미 회원이신가요?

2024년 5월 17일 오전 10:42

 • 

저장 313조회 12,595

댓글 1

    함께 읽은 게시물

    AI와 코딩할 때, 혹시 결과만 말하고 계신가요?
    얼마 전 프로필 페이지를 AI와 함께 만들면서 이상한 걸 발견했어요.

    ... 더 보기

    - YouTube

    youtu.be

     - YouTube

     • 

    저장 13 • 조회 1,381


    🤖 최초의 AI 브라우저, Dia 직접 써봤습니다! 🌐

    ... 더 보기

    6년간의 토이프로젝트 여정을 마무리하며 - 기술블로그 구독서비스 회고록

    ... 더 보기

    6년간의 토이프로젝트 여정을 마무리하며 - 기술블로그 구독서비스 회고록

    taetaetae.github.io

    6년간의 토이프로젝트 여정을 마무리하며 - 기술블로그 구독서비스 회고록

     • 

    댓글 1 • 저장 9 • 조회 1,975


    간만에 재밌게 읽은 기술 포스트

    ... 더 보기

    무진장 힘들었지만 무진장 성장한 개발 이야기

    Medium

    무진장 힘들었지만 무진장 성장한 개발 이야기

    고용노동부에서 주관하는 청년미래플러스 3기를 모집 중이라고 합니다.

    구직자와 재직자 두 가지 트랙을 동시에 모집한다고 하네요.

    • 모집 기간: 6월 15일 ~ 8월 3일

    ... 더 보기

    DDD와 액터모델

    D

    ... 더 보기

    WEBNORI

    wiki.webnori.com

    WEBNORI

     • 

    저장 10 • 조회 1,542