매직 넘버(Magic number)

hwisaac·2023년 2월 25일
0

리팩토링

목록 보기
5/6

매직 넘버(Magic number)는 코드에서 하드 코딩된(literal value) 일정한 값을 의미하는 숫자나 문자열 등을 의미합니다.

매직넘버는 코드 내에서 여러 곳에서 사용되지만 이 값의 의미나 목적은 코드에서 명확하게 알려지지 않습니다.

매직 넘버는 가독성이 떨어지고 유지보수가 어렵게 만들며, 예상치 못한 버그를 발생시키는 원인이 될 수 있습니다.

따라서 매직 넘버 대신에 상수나 변수를 사용하는 것이 좋습니다. 변수나 상수를 사용하면 값을 변경할 때 일괄적으로 변경할 수 있으므로 코드의 유지보수성과 가독성이 향상됩니다.

예시1

예를 들어, 다음과 같은 매직 넘버가 있는 코드가 있다고 가정해봅시다.

function calculateArea(radius) {
  return 3.14 * radius * radius;
}

위 코드에서 3.14는 매직 넘버입니다. 이 값은 그 의미나 목적은 명확하지 않습니다. 따라서 이 값을 PI 상수로 변경하는 것이 좋습니다.

const PI = 3.14;

function calculateArea(radius) {
  return PI * radius * radius;
}

위 코드에서는 PI 상수를 정의하여 매직 넘버를 대체하였습니다. 이렇게 하면 코드의 가독성이 향상되고, PI 값을 변경해야 할 경우 한 곳에서 변경하면 모든 코드에서 일괄적으로 적용됩니다.

예시2

다른 예시로는 파일 확장자나 시간 관련 값 등도 매직 넘버로 사용될 수 있습니다. 예를 들어, 다음과 같은 코드가 있다고 가정해봅시다.

function getFileType(fileName) {
  if (fileName.endsWith(".jpg")) {
    return "image";
  } else if (fileName.endsWith(".mp3")) {
    return "audio";
  } else if (fileName.endsWith(".txt")) {
    return "text";
  } else {
    return "unknown";
  }
}

위 코드에서 ".jpg", ".mp3", ".txt"는 각각 이미지, 오디오, 텍스트 파일의 확장자입니다. 이 값을 직접 사용하면 매직 넘버가 됩니다. 이 값을 상수로 정의하여 매직 넘버를 대체하는 것이 좋습니다.

const IMAGE_EXTENSION = ".jpg";
const AUDIO_EXTENSION = ".mp3";
const TEXT_EXTENSION = ".txt";

function getFileType(fileName) {
  if (fileName.endsWith(IMAGE_EXTENSION)) {
    return "image";
  } else if (fileName.endsWith(AUDIO_EXTENSION)) {
    return "audio";
  } else if (fileName.endsWith(TEXT_EXTENSION)) {
    return "text";
  } else {
    return "unknown";
  }
}

위 코드에서는 IMAGE_EXTENSION, AUDIO_EXTENSION, TEXT_EXTENSION 상수를 정의하여 매직 넘버를 대체하였습니다.

예시3

시간 관련 값이 매직 넘버로 사용될 수 있습니다. 예를 들어, 다음과 같은 코드가 있다고 가정해봅시다.

function calculateAge(birthDate) {
  const currentYear = new Date().getFullYear();
  const birthYear = new Date(birthDate).getFullYear();
  return currentYear - birthYear;
}

위 코드에서 new Date().getFullYear()는 현재 연도를 나타내는 매직 넘버입니다. 이 값을 상수로 정의하여 매직 넘버를 대체하는 것이 좋습니다.

const CURRENT_YEAR = new Date().getFullYear();

function calculateAge(birthDate) {
  const birthYear = new Date(birthDate).getFullYear();
  return CURRENT_YEAR - birthYear;
}

위 코드에서는 CURRENT_YEAR 상수를 정의하여 매직 넘버를 대체하였습니다.

1개의 댓글

comment-user-thumbnail
2024년 7월 9일

A magic number often refers to a special number with significant properties, such as making calculations easier or unlocking unique patterns. In the context of entertainment, finding the right "magic number" can mean discovering the perfect performer to bring joy and amazement to an event. For a memorable celebration, hiring a los angeles birthday party magician can be the magic number that transforms an ordinary party into an extraordinary experience filled with wonder and excitement for all ages.

답글 달기