Intro
- 깨끗한 코드와 오류처리는 확실히 연관성이 있다.
- 상당수 코드 기반은 전적으로 오류 처리 코드에 좌우된다.
- 오류 처리는 중요하지만 오류 처리로 인해 프로그램 논리를 이해하기 어려워진다면 깨끗한 코드가 아니다.
오류 코드보다 에외를 사용하라
- 예전 예외를 지원하지 않는 언어는 오류를 처리하고 보고하는 방법이 제한적이었다.
- 오류 플래그를 설정하거나 호출자에게 오류 코드를 반환하는 방법이 전부였다.
- 이렇게 할 경우 호출자 코드가 복잡해진다. 따라서 예외를 던져야 한다.
- 오류를 사용 할 경우 단순히 보기만 좋은게 아닌 알고리즘과 오류 처리를 분리되어 이해하기 쉬워진다.
public class DeviceController {
...
public void sendShutDown() {
DeviceHandle handle = getHandle(DEV1);
if (handle != DeviceHandle.INVALID) {
retrieveDeviceRecord(handle);
if (record.getStatus() != DEVICE_SUSPENDED) {
pauseDevice(handle);
clearDeviceWorkQueue(handle);
closeDevice(handle);
} else {
logger.log("Device suspended. Unable to shut down");
}
} else {
logger.log("Invalid handle for: " + DEV1.toString());
}
}
...
}
public class DeviceController {
...
public void sendShutDown() {
try {
tryToShutDown();
} catch (DeviceShutDownError e) {
logger.log(e);
}
}
private void tryToShutDown() throws DeviceShutDownError {
DeviceHandle handle = getHandle(DEV1);
DeviceRecord record = retrieveDeviceRecord(handle);
pauseDevice(handle);
clearDeviceWorkQueue(handle);
closeDevice(handle);
}
private DeviceHandle getHandle(DeviceID id) {
...
throw new DeviceShutDownError("Invalid handle for: " + id.toString());
...
}
...
}
Try-Catch-Finally 문부터 작성하라
- 예외에서 프로그램 안에다 범위를 정의한다.
- try 블록은 transaction 과 비슷하다. try 블록에 관계없이 catch 블록은 프로그램을 상태를 일관성 있게 유지해야한다.
- try 블록에서 무슨일이 생기든 호출자가 기대하는 상태를 정의하기 쉬워진다.
@Test(expected = StorageException.class)
public void retrieveSectionShouldThrowOnInvalidFileName() {
sectionStore.retrieveSection("invalid - file");
}
public List<RecordedGrip> retrieveSection(String sectionName) {
return new ArrayList<RecordedGrip>();
}
public List<RecordedGrip> retrieveSection(String sectionName) {
try {
FileInputStream stream = new FileInputStream(sectionName)
} catch (Exception e) {
throw new StorageException("retrieval error", e);
}
return new ArrayList<RecordedGrip>();
}
public List<RecordedGrip> retrieveSection(String sectionName) {
try {
FileInputStream stream = new FileInputStream(sectionName);
stream.close();
} catch (FileNotFoundException e) {
throw new StorageException("retrieval error", e);
}
return new ArrayList<RecordedGrip>();
}
미확인(Unchecked Exception) 예외를 사용하라
- 여러해 동안 논쟁이 있었고 초기엔 확인된 예외(Checked Exception)가 멋진 아이디어로 여겨졌었다.
- 실제로 확인된 예외는 몇가지 장점을 제공하지만 안정적인 소프트웨어 제작에 반드시 필요하지 않다는 사실이 분명해졌다.
- 확인된 오류가 치르는 비용에 상응하는 이익을 제공하는지 따져봐야한다.
- OCP(Open Closed Principle)를 위반한다.
- 하위 단계에서 확인된 예외를 추가하면 상위 단계 메서드 선언부를 전부 고쳐야 한다.
- throws 경로에 위치한 모든 함수가 최하위 함수에서 던지는 예외를 알아야 하므로 캡슐화가 깨진다.
- 때로는 확인된 예외도 유용하지만 일반적으로 비용이 이익보다 더크다.
예외에 의미를 제공하라
- 예외를 던질때는 전후 상황을 충분히 덧붙여야한다.
- 실패한 코드의 의도를 파악하려면 호출 스택만으론 부족하다.
- 오류 메시지에 정보(실패한 연산 이름과 실패 유형)를 담아 예외와 함께 던져야한다.
- 로깅 기능을 사용한다면 catch 블록에서 오류를 기록하도록 충분한 정보를 넘겨줘야한다.
호출자를 고려해 예외 클래스를 정의하라
- 오류를 정의할 때 고려해야할 가장 중요한 관심사는 오류를 잡아내는 방법이 되어야한다.
- 외부 라이브러리를 사용하는 경우 그것들을 wrapping 함으로써 라이브러리 교체 등의 변경이 있는 경우 대응하기 쉬워진다.
- 외부 API를 감싸면 외부 라이브러리와 프로그램 사이의 의존성이 크게 줄어든다.
- 또한 감싸기 클래스에서 외부 API를 호출하는 대신 테스트 코드를 넣어주는 방법으로 테스트도 더 간편해진다.
- 추가로 외부 라이브러리의 설계 방식에 발목 잡히지 않는다. 프로그램이 사용하기 편리한 API를 정의하면 된다.
- 흔히 예외 클래스가 하나만 있어도 충분한 코드가 많다.
ACMEPort port = new ACMEPort(12);
try {
port.open();
} catch (DeviceResponseException e) {
reportPortError(e);
logger.log("Device response exception", e);
} catch (ATM1212UnlockedException e) {
reportPortError(e);
logger.log("Unlock exception", e);
} catch (GMXError e) {
reportPortError(e);
logger.log("Device response exception");
} finally {
...
}
LocalPort port = new LocalPort(12);
try {
port.open();
} catch (PortDeviceFailure e) {
reportError(e);
logger.log(e.getMessage(), e);
} finally {
...
}
public class LocalPort {
private ACMEPort innerPort;
public LocalPort(int portNumber) {
innerPort = new ACMEPort(portNumber);
}
public void open() {
try {
innerPort.open();
} catch (DeviceResponseException e) {
throw new PortDeviceFailure(e);
} catch (ATM1212UnlockedException e) {
throw new PortDeviceFailure(e);
} catch (GMXError e) {
throw new PortDeviceFailure(e);
}
}
...
}
정상적인 흐름을 정의하라
- 외부 API를 감싸 독자적인 예외를 던지고, 코드 위에 처리기(catch 문) 를 정의해 중단된 계산을 처리할 경우
- 대개는 멋진 처리 방식이지만, 때로는 중단이 적합하지 않은 때도 있다.
- 추가) 내부에서 오류 처리를 하여 호출하는 쪽에선 정상적인 흐름으로 처리되게 해야한다는 의미 같음
try {
MealExpenses expenses = expenseReportDAO.getMeals(employee.getID());
m_total += expenses.getTotal();
} catch(MealExpensesNotFound e) {
m_total += getMealPerDiem();
}
MealExpenses expenses = expenseReportDAO.getMeals(employee.getID());
m_total += expenses.getTotal();
public class PerDiemMealExpenses implements MealExpenses {
public int getTotal() {
}
}
public class ExpenseReportDAO {
...
public MealExpenses getMeals(int employeeId) {
MealExpenses expenses;
try {
expenses = 예외가 발생할수도 있는 내부 코드;
} catch(MealExpensesNotFound e) {
expenses = new PerDiemMealExpenses();
}
return expenses;
}
...
}
- 위와 같은 방법을 특수 사례 패턴(Special Case Pattern) 이라 부른다.
- 클래스를 만들거나 객체를 조작하여 클라이언트 코드가 예외 상황을 처리하지 않도록 만든다.
null을 반환하지 마라
- null 을 반환하는 습관은 흔히 저지르는 오류 유발 행위이다.
- null 을 반환하면 코드 일거리를 늘릴뿐 아니라 호출자에게 문제를 떠넘기는 것이다.
- 외부 api가 null을 반환한다면 감싸기 메서드를 구현해 예외를 던지거나 특수 사례 객체를 반환하는 방식을 고려해야한다.
public void registerItem(Item item) {
if (item != null) {
ItemRegistry registry = peristentStore.getItemRegistry();
if (registry != null) {
Item existing = registry.getItem(item.getID());
if (existing.getBillingPeriod().hasRetailOwner()) {
existing.register(item);
}
}
}
}
List<Employee> employees = getEmployees();
if (employees != null) {
for(Employee e : employees) {
totalPay += e.getPay();
}
}
List<Employee> employees = getEmployees();
for (Employee e : employees) {
totalPay += e.getPay();
}
public List<Employee> getEmployees() {
if ( .. 직원이 없다면 .. )
return Collections.emptyList();
}
}
null을 전달하지마라
- null을 반환하는 방식도 나쁘지만 null을 메서드로 넘전달 하는 방식은 더 나쁘다.
- 정상적인 인수로 null을 기대하는 API가 아니라면 메서드로 null을 전달하는 코드는 최대한 피해야한다.
- 대다수의 프로그래밍 언어는 호출자가 실수로 넘기는 null 을 적절히 처리하는 방법이 없다.
- 그렇다면 애초에 null을 넘기지 못하도록 금지하는 정책이 합리적이다.
- 이럴 경우 부주의한 실수를 저지를 확률도 작아진다.
public class MetricsCalculator {
public double xProjection(Point p1, Point p2) {
return (p2.x – p1.x) * 1.5;
}
...
}
public class MetricsCalculator {
public double xProjection(Point p1, Point p2) {
if(p1 == null || p2 == null){
throw InvalidArgumentException("Invalid argument for MetricsCalculator.xProjection");
}
return (p2.x – p1.x) * 1.5;
}
}
public class MetricsCalculator {
public double xProjection(Point p1, Point p2) {
assert p1 != null : "p1 should not be null";
assert p2 != null : "p2 should not be null";
return (p2.x – p1.x) * 1.5;
}
}
결론
- 깨끗한 코드는 읽기도 좋아햐 하지만 안정성도 높아야 한다. 이둘은 상충하는 목표가 아니다.
- 오류 처리를 프로그램 논리와 분리하면 독립적인 추론이 가능해지며 코드 유지보수성도 크게 높아진다.