TIL 클린코드 - 6장. 객체와 자료 구조

노마드코더, 북클럽, 노개북, 노마드북클럽, 코딩, 개발자, TIL

TIL (Today I Learned)

2022.05.04

오늘 읽은 범위

6장. 객체와 자료 구조

책에서 기억하고 싶은 내용을 써보세요.

오늘 읽은 소감은? 떠오르는 생각을 가볍게 적어보세요


getter와 setter를 사용하세요

JavaScript는 인터페이스와 타입을 가지고있지 않고 이러한 패턴을 적용하기가 힘듭니다. 왜냐하면 public이나 private같은 키워드가 없기 때문이죠. 그렇기 때문에 getter 및 setter를 사용하여 객체의 데이터에 접근하는 것이 객체의 속성을 찾는 것보다 훨씬 낫습니다. “왜요?”라고 물으실 수도 있겠습니다. 왜 그런지에 대해서 몇 가지 이유를 두서없이 적어봤습니다.

안좋은 예:

function makeBankAccount() {
  // ...

  return {
    // ...
    balance: 0,
  };
}

const account = makeBankAccount();
account.balance = 100;

좋은 예:

function makeBankAccount() {
  // private으로 선언된 변수
  let balance = 0;

  // 아래 return을 통해 public으로 선언된 "getter"
  function getBalance() {
    return balance;
  }

  // 아래 return을 통해 public으로 선언된 "setter"
  function setBalance(amount) {
    // ... balance를 업데이트하기 전 검증로직
    balance = amount;
  }

  return {
    // ...
    getBalance,
    setBalance,
  };
}

const account = makeBankAccount();
account.setBalance(100);

객체에 비공개 멤버를 만드세요

클로저를 이용하면 가능합니다. (ES5 이하에서도)

안좋은 예:

const Employee = function (name) {
  this.name = name;
};

Employee.prototype.getName = function getName() {
  return this.name;
};

const employee = new Employee('John Doe');
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined

좋은 예:

function makeEmployee(name) {
  return {
    getName() {
      return name;
    },
  };
}

const employee = makeEmployee('John Doe');
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe