๐Ÿ˜€ gaurd Clauses๊ฐ€ ๋ญ์ง€?

์œ„ํ‚คํ”ผ๋””์•„์—์„œ guard code๋ฅผ ์•„๋ž˜์™€ ๊ฐ™์ด ์„ค๋ช…ํ•œ๋‹ค.

๐Ÿ’ก Regardless of which programming language is used, guard code or a guard clause is a check of integrity preconditions used to avoid errors during execution. - Wikipedia

guard๋Š” ์ „์ œ์กฐ๊ฑด์˜ ๋ฌด๊ฒฐ์„ฑ์„ ํ™•์ธํ•˜๋Š” ์ฝ”๋“œ๋ผ๊ณ  ์ ํ˜€์žˆ๋‹ค. ์ด๋Š” guard code ์ดํ›„ ์‹คํ–‰๋˜๋Š” ์ฝ”๋“œ๋Š” ์ „์ œ์กฐ๊ฑด์„ ๋งŒ์กฑํ•œ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค. ์ด๋ฅผ ์ด์šฉํ•˜์—ฌ, if๋ฌธ์˜ ์ค‘์ฒฉ์„ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค.

๐Ÿง ์–ธ์ œ ์‚ฌ์šฉํ•ด?

์ฃผ๋กœ if - else if๋ฌธ์ด ์—ฌ๋Ÿฌ๊ฐœ ์ค‘์ฒฉํ•  ๋•Œ ์‚ฌ์šฉ์„ ๊ณ ๋ คํ•ด๋ณผ ์ˆ˜ ์žˆ๊ณ , if๋ฌธ์˜ ์กฐ๊ฑด ์ค‘ ํ•œ ์กฐ๊ฑด์˜ ๋ถ„๊ธฐ๋ฌธ์ด ๊ฐ„๋‹จํ•˜๋ฉด ์‚ฌ์šฉํ•˜๊ธฐ์— ์ข‹๋‹ค.

guardํ•˜๊ณ  ์‹ถ์€ ์˜ˆ

const convertUser = function(user) {
  if (user) {
    if(user.country === 'KOR' || user.country === 'NZL') {
      if(user.language === 'en') {
        // ๋ณต์žกํ•œ ์ฝ”๋“œ
        return user;
      } else {
        throw Error('์˜์–ด์•ˆ์จ์š”');
      }
    } else {
      throw Error('ํ•œ๊ตญ์ธ, ๋‰ด์งˆ๋žœ๋“œ์ธ์ด ์•„๋‹ˆ์˜ˆ์š”');
    }
  } else {
    throw Error('์œ ์ €๊ฐ€ ์—†์–ด์š”.');
  }
}

โ“ ์™œ ์‚ฌ์šฉํ•ด?

ํ‰ํƒ„ํ™” ์ž‘์—…์„ ํ†ตํ•ด ์ฝ”๋“œ๋ฅผ ์ฝ๊ธฐ ์‰ฝ๊ฒŒ ๋งŒ๋“ค์–ด ์ค€๋‹ค.

๊ทธ๋Ÿฌ๋ฉด ์œ„ ์ฝ”๋“œ๋Š” ์™œ ์ฝ๊ธฐ ํž˜๋“ค๊นŒ?

๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป ์–ด๋–ป๊ฒŒ ์‚ฌ์šฉํ•ด?

const convertUser = function(user) {
  if (!user) {
    throw Error('์œ ์ €๊ฐ€ ์—†์–ด์š”.');
  }

  if (!isNzlOrKor(user)) {
    throw Error('ํ•œ๊ตญ์ธ, ๋‰ด์งˆ๋žœ๋“œ์ธ์ด ์•„๋‹ˆ์˜ˆ์š”');
  };

  if (!isAvailableEnglish(user)) {
    throw Error('์˜์–ด์•ˆ์จ์š”');
  }

  // ๋ณต์žกํ•œ ์ฝ”๋“œ
  return user;
}

const isNzlOrKor = function(user) {
 return user.country === 'KOR' || user.country === 'NZL'
}

const isAvailableEnglish = function(user) {
 return user.language === 'en'
}

์ฐธ๊ณ : Refactoring: Guard Clauses