๐ย ์ค๋ ์ฝ์ ๋ฒ์ : 7. ์ค๋ฅ์ฒ๋ฆฌ (137~142p)
try {
MealExpenses expenses = expenseReportDAO.getMeals(employee.getID());
m_total += expenses.getTotal();
} catch (MealExpensesNotFound e) {
m_total += getMealPerDiem();
}
ํน์์ํฉ์ ์ฒ๋ฆฌํ ํ์๊ฐ ์์ผ๋ฉด ๋ ์ข๊ฒ ๋คpublic class PerDiemMealExpenses implements MealExpenses {
public int getTotal() {
// ๊ธฐ๋ณธ๊ฐ์ผ๋ก ์ผ์ผ ๊ธฐ๋ณธ ์๋น๋ฅผ ๋ฐํํ๋ค. }
}
}
์์ ๊ฐ์ด ๊ธฐ๋ณธ๊ฐ์ ๋ฐํํ๋ฉด ์ค๋จํ ํ์๊ฐ ์๋คMealExpenses expenses = expenseReportDAO.getMeals(employee.getID());
m_total += expenses.getTotal();
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();
}
}
์ ๊ฒฝ์ฐ์์ getEmployees๋ฅผ ์๋์ ๊ฐ์ด ๋ณ๊ฒฝ
public List < Employee > getEmployees() {
if (..์ง์์ด ์๋ค๋ฉด..)
return Collections.emptyList();
}
empty List ๋ฅผ ๋ฐํํ์์ผ๋ฏ๋ก null ์ฒดํฌ ์์ด ์งํ
List < Employee > employees = getEmployees();
for (Employee e: employees) {
totalPay += e.getPay();
}
public class MetricsCalculator {
public double xProjection(Point p1, Point p2) {
return (p2.xโ p1.x) * 1.5;
}
...
}
๋๊ตฐ๊ฐ Null ์ ์ ๋ฌํ๋ค๋ฉดcalculator.xProjection(null, new Point(12, 13));
โ NullPointerException ๋ฐ์ ๋ฐฉ๋ฒ1. ์๋ก์ด ์์ธ ์ ํ์ ๋ง๋ค์ด ๋์ง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;
}
}
๊ธฐ์กด๋ณด๋ค๋ ๋ซ์ง๋ง InvalidArgumentException ์ฒ๋ฆฌ๊ธฐ๊ฐ ํ์ํ๋ค ๋ฐฉ๋ฒ2. assert๋ฌธ์ ์ฌ์ฉ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;
}
}
๋ณด๊ธฐ์๋ ํธํ์ง๋ง ์ฌ์ ํ null ์ ๋ฌ ๋์์ ๋ ์ค๋ฅ๊ฐ ๋ฐ์ํ๊ธดํจ