Java/πŸ“• Effective Java

[Effective Java] 객체 생성과 파괴 δΈ‹

soogoori 2024. 9. 20. 22:09

4. μΈμŠ€ν„΄μŠ€ν™”λ₯Ό λ§‰μœΌλ €λ©΄ private μƒμ„±μž μ‚¬μš©

 

 

 

5. μžμ›μ„ 직접 λͺ…μ‹œν•˜μ§€ 말고 의쑴 객체 μ£Όμž… μ‚¬μš© 

μ‚¬μš©ν•˜λŠ” μžμ›μ— 따라 λ™μž‘μ΄ λ‹¬λΌμ§€λŠ” ν΄λž˜μŠ€μ—λŠ” 정적 μœ ν‹Έλ¦¬ν‹° ν΄λž˜μŠ€λ‚˜ μ‹±κΈ€ν„΄ 방식 적합 X
πŸ‘‰ μΈμŠ€ν„΄μŠ€λ₯Ό 생성할 λ•Œ μƒμ„±μžμ— ν•„μš”ν•œ μžμ›μ„ λ„˜κ²¨μ£ΌλŠ” 방식 = 의쑴 객체 μ£Όμž…  

 

  • μƒμ„±μžμ— μžμ› νŒ©ν† λ¦¬λ₯Ό λ„˜κ²¨μ€Œ
✨ νŒ©ν† λ¦¬

πŸ‘‰ ν˜ΈμΆœν•  λ•Œλ§ˆλ‹€ νŠΉμ • νƒ€μž…μ˜ μΈμŠ€ν„΄μŠ€λ₯Ό λ°˜λ³΅ν•΄μ„œ λ§Œλ“€μ–΄μ£ΌλŠ” 객체 
public class SpellChecker{
	private final Lexicon dictionary;
    
    public SpellChecker(Lexicon dictionary){
    	this.dictionary = Objects.requireNonNull(dictionary);
    }
    
    public boolean isValid(String word){ ... }
    public List<String> suggestions(String typo) { ... }
}

 

 

6. λΆˆν•„μš”ν•œ 객체 생성 ν”Όν•˜κΈ°

 

 

 

 

7. λ‹€ μ“΄ 객체 μ°Έμ‘° ν•΄μ œν•˜κΈ°

 

 

 

 

8.  finalizer와 cleaner μ‚¬μš© 자제

 

 

 

 

9.  try-finallyλ³΄λ‹€λŠ” try-with-resources μ‚¬μš©

μžμ›μ΄ λ‘˜ 이상이라면 try-finally 방식은 지저뢄함
try-with-resources(μžλ°” 7)을 μ‚¬μš©ν•΄ 볡수의 μžμ›μ„ μ²˜λ¦¬ν•˜λŠ” 데 가독성을 높일 수 있음

 

public class TryWithResourcesExample {
    public static void main(String[] args) {
        // 파일 경둜λ₯Ό 지정
        String filePath = "example.txt";
        
        // try-with-resources 블둝을 μ‚¬μš©ν•˜μ—¬ μžμ›μ„ μžλ™μœΌλ‘œ λ‹«μŒ
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

πŸ‘‰ ν•΄λ‹Ή μžμ›μ΄ AutoCloseable μΈν„°νŽ˜μ΄μŠ€λ₯Ό κ΅¬ν˜„ν•΄μ•Όν•¨(μžλ°” λΌμ΄λΈŒλŸ¬λ¦¬μ™€ μ„œλ“œνŒŒν‹° λΌμ΄λΈŒλŸ¬λ¦¬λ“€μ˜ μˆ˜λ§Žμ€ ν΄λž˜μŠ€μ™€ μΈν„°νŽ˜μ΄μŠ€κ°€ 이미 κ΅¬ν˜„ν•˜κ±°λ‚˜ ν™•μž₯ν•΄λ‘ )