NMP-Study / EffectiveJava2022

Effective Java Study 2022
5 stars 0 forks source link

아이템 24. 멤버 클래스는 되도록 static으로 만들라 #24

Closed okhee closed 2 years ago

KimYunsang-v commented 2 years ago

중첩 클래스 (nested class)

새로운 클래스가 필요한데 이 클래스를 하나의 클래스에서만 사용한다면 중첩 클래스 사용

중첩 클래스 종류

정적 멤버 클래스 (static class)

public static helper class ```java public class OuterClass { public static class OuterClassHelper { static final String FUNCTION_1 = "..."; static final String FUNCTION_2 = "..."; } } class TestClass { public static void main(String[] args) { System.out.println(OuterClass.OuterClassHelper.FUNCTION_1); } } ```
HashMap의 Map.Entry 구현부 ```java static class Node implements Map.Entry { final int hash; final K key; V value; Node next; Node(int hash, K key, V value, Node next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } public final K getKey() { return key; } public final V getValue() { return value; } public final String toString() { return key + "=" + value; } public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } public final boolean equals(Object o) { if (o == this) return true; if (o instanceof Map.Entry) { Map.Entry e = (Map.Entry)o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true; } return false; } } ```

멤버 클래스에서 바깥 인스턴스에 접근할 일이 없다면 무조건 static 으로 선언하라!

비정적 멤버 클래스

HashMap의 EntrySet 구현부 ```java final class EntrySet extends AbstractSet> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator> iterator() { return new EntryIterator(); } public final boolean contains(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry) o; Object key = e.getKey(); Node candidate = getNode(hash(key), key); return candidate != null && candidate.equals(e); } public final boolean remove(Object o) { if (o instanceof Map.Entry) { Map.Entry e = (Map.Entry) o; Object key = e.getKey(); Object value = e.getValue(); return removeNode(hash(key), key, value, true, true) != null; } return false; } public final Spliterator> spliterator() { return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0); } public final void forEach(Consumer> action) { Node[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (Node e : tab) { for (; e != null; e = e.next) action.accept(e); } if (modCount != mc) throw new ConcurrentModificationException(); } } } ```

익명 클래스 (Anonymous class)

람다를 쓰자

지역 클래스 (Local class)

잘 안씀

qlqhqo2341 commented 2 years ago

Adapter 예시가 Executors에 괜찮은 클래스가 하나 있었네요. https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/concurrent/Executors.java#L569