Skip to content

Commit

Permalink
Merge pull request #342 from Wave1994-Hoon/week12-tmp
Browse files Browse the repository at this point in the history
[#71][2κΈ°] ν•„μš”μ—†λŠ” 검사 μ˜ˆμ™Έ μ‚¬μš©μ€ ν”Όν•˜λΌ
  • Loading branch information
ksy90101 authored Oct 25, 2021
2 parents 87682dc + e3531ba commit d020b99
Showing 1 changed file with 114 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# Item 71. ν•„μš”μ—†λŠ” 검사 μ˜ˆμ™Έ μ‚¬μš©μ€ ν”Όν•˜λΌ
## 1. 핡심정리
- κΌ­ ν•„μš”ν•œ κ³³μ—λ§Œ μ‚¬μš©ν•œλ‹€λ©΄, 검사 μ˜ˆμ™ΈλŠ” ν”„λ‘œκ·Έλž¨μ˜ μ•ˆμ •μ„±μ„ λ†’μ—¬μ€€λ‹€. ν•˜μ§€λ§Œ λ‚¨μš©ν•˜λ©΄ μ“°κΈ° μ–΄λ €μš΄ API λ₯Ό λ‚³λŠ”λ‹€.
- μ˜ˆμ™Έ μƒν™©μ—μ„œ 볡ꡬ할 방법이 μ—†λ‹€λ©΄ `비검사 μ˜ˆμ™Έ`λ₯Ό λ˜μ§€μž.
- 볡ꡬ가 κ°€λŠ₯ν•˜κ³  ν˜ΈμΆœμžκ°€ κ·Έ 처리λ₯Ό ν•΄μ£ΌκΈΈ λ°”λž€λ‹€λ©΄, μš°μ„  μ˜΅μ…”λ„μ„ λ°˜ν™˜ν•΄λ„ 될지 κ³ λ―Όν•˜μž.
- μ˜΅μ…”λ„λ§ŒμœΌλ‘œλŠ” 상황을 μ²˜λ¦¬ν•˜κΈ°μ— μΆ©λΆ„ν•œ 정보λ₯Ό μ œκ³΅ν•  수 없을 λ•Œλ§Œ 검사 μ˜ˆμ™Έλ₯Ό λ˜μ§€μž.

<br>

## 2. 검사 μ˜ˆμ™Έ (Checked Exception)
- 검사 μ˜ˆμ™ΈλŠ” λ°œμƒν•œ 문제λ₯Ό ν”„λ‘œκ·Έλž˜λ¨Έκ°€ μ²˜λ¦¬ν•˜μ—¬ μ•ˆμ •μ„±μ„ λ†’νž 수 μžˆλ‹€.
- λ¬Όλ‘ , κ³Όν•˜κ²Œ μ‚¬μš©ν•˜λ©΄ 였히렀 μ“°κΈ° λΆˆνŽΈν•œ APi κ°€ 될 수 μžˆλ‹€.
- (1) try/catch 블둝, throws
```java
public class Example {

public void example() {

try {

} catch (IOException e) {

}

try {

} catch (IOException e) {

}

try {

} catch (IOException e) {

}

...
}
}
```
- (2) Java 8, Stream
```java
public class Test {

public static void main(String[] args) {
String[] names = {"μžλ°”", "파이썬", "κ³ ", "Trigger"};

Arrays.stream(names)
.map(Example::verifyName) // <--- compile error
.collect(toSet());
}

public static class Example {

public String verifyName(String name) throws Exception {
if (name == "trigger") {
throw new Exception("fail");
}
return name;
}
}

}
```


<br>


## 3. 검사 μ˜ˆμ™Έλ₯Ό νšŒν”Όν•˜λŠ” 방법
### (1) Optional
- 검사 μ˜ˆμ™Έλ₯Ό λ˜μ§€λŠ” λŒ€μ‹  λ‹¨μˆœνžˆ 빈 μ˜΅μ…”λ„μ„ λ°˜ν™˜ν•˜λ©΄ λœλ‹€.
- μ˜ˆμ‹œ
- AS-IS
```java
Long userId = 1L;
try {
User user = userService.findUserById(userId);
} catch (Exception e) {
log.error("fail to find user, userId: {}", userId)
user = new User(userId);
}
```
- TO-BE
```java
Long userId = 1L;

User user = repository.findUserById(userId)
.orElseGet(() -> new User(userId));
```

<br>

### (2) λ©”μ„œλ“œλ₯Ό 두 개둜 λΆ„ν• ν•˜μ—¬ 비검사 μ˜ˆμ™Έλ‘œ λ°”κΎΌλ‹€.
- 이 λ°©μ‹μ—μ„œ 첫 번째 λ©”μ„œλ“œλŠ” μ˜ˆμ™Έκ°€ λ˜μ Έμ§ˆμ§€ μ—¬λΆ€λ₯Ό boolean κ°’μœΌλ‘œ λ°˜ν™˜ν•œλ‹€.
- μ˜ˆμ‹œ
- AS-IS
```java
try {
obj.action(args);
} catch (TheCheckedException e) {
... // μ˜ˆμ™Έ 상황에 λŒ€μ²˜ν•œλ‹€.
}
```
- TO-BE
```java
if(obj.actionPermitted(args)){
obj.action(args);
} else {
... // μ˜ˆμ™Έ 상황에 λŒ€μ²˜ν•œλ‹€.
}
```

- ν•˜μ§€λ§Œ μ™ΈλΆ€ μš”μ•ˆμ— μ˜ν•˜μ—¬ μƒνƒœκ°€ λ³€ν•  수 μžˆλ‹€λ©΄, 이 방법은 적절치 μ•Šλ‹€.

0 comments on commit d020b99

Please sign in to comment.