🕊️ [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

 • 

저장 305조회 12,133

댓글 0