Replace Primitive With Object, ๊ธฐ๋ณธํ˜•์„ ๊ฐ์ฒด๋กœ ๋ฐ”๊พธ๊ธฐ๋ฅผ ์•Œ์•„๋ณด์ž.

์š”์•ฝ

์ฝ”๋“œ

orders.filter(o => "high" === o.priority || "rush" === o.priority)
orders.filter(o => o.priority.higherThan(new Priority("normal")))

๋ฐฐ๊ฒฝ

  • ๊ฐœ๋ฐœ ์ดˆ๊ธฐ์—๋Š” ๋‹จ์ˆœํ•œ ์ •๋ณด๋ฅผ ์ˆซ์ž๋‚˜ ๋ฌธ์ž์—ด ๊ฐ™์ด ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.
  • ๊ทธ๋Ÿฐ๋ฐ ์ง„ํ–‰๋  ์ˆ˜๋ก ์ด ์ •๋ณด๋“ค์ด ๊ฐ„๋‹จํ•˜์ง€ ์•Š๊ฒŒ ๋ณ€ํ•˜๊ธฐ ์ผ์‘ค๋‹ค.
  • ๋‹จ์ˆœํžˆ ์ถœ๋ ฅ ์ด์ƒ์˜ ๊ธฐ๋Šฅ์ด ํ•„์š”ํ•ด์ง„๋‹ค๋ฉด, ์ „์šฉ ํด๋ž˜์Šค๋กœ ๋ฌถ๋Š”๊ฒŒ ์ข‹๋‹ค.
  • ์‹œ์ž‘์€ ๋ณ„๊ฑฐ ์—†๊ฒ ์ง€๋งŒ, ํŠน๋ณ„ํ•œ ๋™์ž‘์ด ํ•„์š”ํ•ด ์ง€๊ฒŒ ๋˜๋ฉด ์•„์ฃผ ํŽธ๋ฆฌํ•ด์ง„๋‹ค.
  • ํ•จ๊ป˜ ๋ฌถ์„ ์ˆ˜ ์žˆ๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๋ชจ์•„๋‘๋Š” ๊ฒƒ์€ ๊ณง ํ•„์š”ํ•œ ๋™์ž‘๋„ ํ•จ๊ป˜ ๋”ฐ๋ผ๊ฐ„๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.

์ ˆ์ฐจ

  1. ์•„์ง ๋ณ€์ˆ˜๋ฅผ ์บก์Šํ™”ํ•˜์ง€ ์•Š์•˜๋‹ค๋ฉด ์บก์Šํ™”ํ•œ๋‹ค.
  2. ๋‹จ์ˆœํ•œ ๊ฐ’ ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ ๋‹ค.
  3. ์ •์  ๊ฒ€์‚ฌ๋ฅผ ์ˆ˜ํ–‰ํ•œ๋‹ค.
  4. ๋ณ€์ˆ˜๋ฅผ ํ•ด๋‹น ํด๋ž˜์Šค ์ธ์Šคํ„ด์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋„๋ก ๋ณ€๊ฒฝํ•œ๋‹ค.

์˜ˆ์‹œ

class Order {
    constructor(data) {
        this.priority = data.priority;
    }
}
 
// client 1
highPriorityCount = orders.filter(o => "high" === o.priority || "rush" === o.priority).length;
  • ์šฐ์„ ์ˆœ์œ„ ์ด ๊ฐ’์ด ์ง€๊ธˆ ๊ธฐ๋ณธํ˜•์ธ๋ฐ, ์–˜๊ฐ€ ์ปค์งˆ ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ด๋ณด์ž.
  • ์บก์Šํ™”๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜์ž.
class Order {
    constructor(data) {
        this._priority = data.priority;
    }
    get priority() {return this._priority;}
    set priority(aString) {this._priority = aString;}
}
  • ๋‹ค์Œ์œผ๋กœ ํด๋ž˜์Šค๋กœ ๋งŒ๋“ค์–ด์•ผ ํ•œ๋‹ค.
class Priority {
    constructor(value) {
        this._value = value;
    }
 
    toString() {return this._value;}
}
 
class Order {
    constructor(data) {
        this._priority = data.priority;
    }
    get priority() {return this._priority;}
    set priority(aString) {this._priority = new Priority(aString);}
}
 
// client 1
highPriorityCount = orders.filter(o => "high" === o.priority || "rush" === o.priority).length;
  • ํด๋ž˜์Šค ํ•˜๋‚˜ ๋งŒ๋“ค์–ด์ฃผ๊ณ , Order์—์„œ๋Š” ์ด ํด๋ž˜์Šค ์ธ์Šคํ„ด์Šค๋ฅผ ํ™œ์šฉํ•˜๋„๋ก ๋ณ€๊ฒฝํ•œ๋‹ค.
  • priority() ํ•จ์ˆ˜์ž์ฒด์˜ ์˜๋ฏธ์™€ ๋‹ค๋ฅด๊ธฐ ๋•Œ๋ฌธ์— prioirtyString()์œผ๋กœ ๋ณ€๊ฒฝํ•œ๋‹ค.
class Priority {
    constructor(value) {
        this._value = value;
    }
 
    toString() {return this._value;}
}
 
class Order {
    constructor(data) {
        this._priority = data.priority;
    }
    get priorityString() {return this._priority.toString();}
    set priority(aString) {this._priority = new Priority(aString);}
}
 
// client 1
highPriorityCount = orders.filter(o => "high" === o.priorityString || "rush" === o.priorityString).length;

Reference