-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
104 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
# 5. 더 좋은 액션 만들기 | ||
|
||
## 비즈니스 요구 사항과 설계를 맞추기 | ||
|
||
무료 배송인지 확인하는 로직이 필요하다. | ||
|
||
```javascript | ||
function gets_free_shipping(total, item_price) { | ||
// 이 인자는 요구사항에 맞지 않다. | ||
return item_price + total >= 20; | ||
} | ||
``` | ||
|
||
```javascript | ||
function calc_total(cart) { | ||
var total = 0; | ||
for (var i = 0; i < cart.length; i++) { | ||
var item = cart[i]; | ||
total += item.price; | ||
} | ||
return total; | ||
} | ||
``` | ||
|
||
위 코드와 아래코드를 보면 장바구니 합계를 계산하는 코드가 중복되어있다. | ||
|
||
위의 코드를 아래와 같이 바꿔보자 | ||
|
||
```javascript | ||
gets_free_shipping(total, item_price) -> gets_free_shipping(cart) | ||
``` | ||
|
||
이렇게 바꿈으로써 장바구니가 무료 배송인지 알려줄 수 있게 되었다. | ||
|
||
## 비즈니스 요구 사항과 함수를 맞추기 | ||
|
||
새 시그니처에 알맞는 구현을 하기 | ||
|
||
```javascript | ||
function gets_free_shipping(cart) { | ||
// 이 인자는 요구사항에 맞지 않다. | ||
return calc_total(cart) >= 20; | ||
} | ||
``` | ||
|
||
## 원칙 : 암묵적 입력과 출력은 적을수록 좋다 | ||
|
||
- 어떤 함수에 암묵적 입력과 출력이 존재한다면, 다른 컴포넌트와 강하게 연결된 컴포넌트라고 할 수 있다. | ||
- 이런 함수는 아무때나 실행할 수 없기 때문에 테스트하기 어렵다. | ||
- 때문에 암묵적 입력을 인자로 받아오고, 명시적으로 값을 return할 수 있도록 수정해야한다. | ||
|
||
## 계산 분류하기 | ||
|
||
주어진 계산 안에서도 각각 무엇에 대한 계산인지를 분류해낼 수 있다. 우리가 작성한 예제에서는 장바구니 구조, 제품에 대한 구조, 비즈니스 규칙 등등의 도메인이 존재한다. 때문에 이런 각각의 도메인에 따라서 또 계산을 분류해낼 수 있다. | ||
|
||
```javascript | ||
function add_item(cart, name, price) { | ||
var new_cart = cart.slice(); | ||
new_cart.push({ | ||
name: name, | ||
price: price, | ||
}); | ||
return new_cart; | ||
} | ||
``` | ||
|
||
이 함수는 cart와 item에 대한 구조를 모두 알고 있다. item에 관한 코드를 별도의 함수로 분리해보자. | ||
|
||
```javascript | ||
function make_cart_item(name, price) { | ||
return { | ||
name: name, | ||
price: price, | ||
}; | ||
} | ||
``` | ||
|
||
```javascript | ||
function add_item(cart, item) { | ||
var new_cart = cart.slice(); | ||
new_cart.push(item); | ||
|
||
return new_cart; | ||
} | ||
|
||
add_item(shopping_cart, make_cart_item("shoes", 3.45)); | ||
``` | ||
|
||
이렇게 도메인에 따라서 계산을 분류할 수 있다. | ||
함수를 작은 단위로 분리하는 것을 보여준 좋은 예시인 것 같음. | ||
|
||
또 여기서 카피-온-라이트 패턴을 함수로 빼내보자 | ||
|
||
```javascript | ||
function add_element_last(array, elem) { | ||
var new_array = array.slice(); | ||
new_array.push(elem); | ||
return new_array; | ||
} | ||
|
||
function add_item(cart, item) { | ||
return add_element_last(cart, item); | ||
} | ||
``` |