GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — 아이템 54. null이 아닌, 빈 컬렉션이나 배열을 반환하라 - Fin · Issue #138 · Study-2-Effective-Java/Effective-Java Open Labels 8장 메서드이펙티브 자바 8장 (메서드)이펙티브 자바 8장 (메서드) DescriptionDiscussed in https://github.com/orgs/Study-2-Effective-Java/discussions/135Originally posted by bunsung92 February 22, 2023 Table of contents generated with markdown-toc 0. 들어가기에 앞서 🤔아래와 같은 public List<Cheese> getCheeses() { return cheesesInStock.isEmpty() ? null : new ArrayList<>(cheesesInStock); } 해당 메서드는 null을 반환할 수 있으므로, null 을 리턴 받게 된 다음 이어질 로직에서는 null을 대비하는 방어 코드를 작성해야 한다. 이보다 좋은 방법은 없을까? 1. null이 아닌, 빈 컬렉션이나 배열을 반환하라 ✨사실 개발자가 처리하고 대비해야 할 null은 수 없이 많다. 물론 하나하나 다 처리해야한다. 1.1 빈 컬렉션을 반환null 대신에 다음과 같이 빈 컬렉션을 반환할 수 있다. public List<Cheese> getCheeses() { return new ArrayList<>(cheesesInStock); } null 을 반환하는 코드랑 크게 다르지 않지만 이는 분명 이점이 있다.
근데 이 마저도 만석 지하철을 3번 보내면은 화가 나는 해당 아이템을 정리 중인 본인 입장에서는 불편하다. 한번 더 방법을 찾아보자. 1.2 빈 불변 컬렉션 반환Collections 를 이용하면 빈 불변 컬렉션을 반환할 수 있다. public List<Cheese> getCheeses() { return cheesesInStock.isEmpty() ? Collections.emptyList() : new ArrayList<>(cheesesInStock); }
1.3 배열배열은 더 간단하다. 빈 배열을 반환하거나, 길이 0 배열을 미리 선언해두고 불변인 배열을 만들어 사용하면 된다. 2. 핵심정리 📚언젠가 메서드에 null 을 반환하고 있다면 null 이 아닌 빈 배열이나 컬렉션을 반환하자. 3. 회고 🧹2023.02.23 목 null 처리의 대가는 Optional로 알고 있었다. 항상 의심하고
ActivityMetadataMetadataAssigneesLabels8장 메서드이펙티브 자바 8장 (메서드)이펙티브 자바 8장 (메서드) TypeProjectsMilestoneRelationshipsDevelopmentIssue actions |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |