욱'S 노트

Replace Magic Number with Symbolic Constants - 매직넘버 심볼릭 상수 치환 본문

Methdology/Refactoring

Replace Magic Number with Symbolic Constants - 매직넘버 심볼릭 상수 치환

devsun 2015. 6. 8. 18:17

문제점


매직넘버를 사용합니다.


매직넘버란 무엇인가 살펴보자면 아래와 같은 코드를 사용하고 있습니다.


if (100 < input.length())


이렇게 되었을 경우 문제점은


1. 의미를 이해하기 어렵습니다.

2. 복수의 장소에서 사용된다면 변경하기 힘듭니다.


해결책


상수를 사용하면 됩니다.


public static final int MAX_INPUT_LENGTH = 100;



연습문제 


문제

public class Robot {
private final String name;

public Robot(String name) {
this.name = name;
}

public void order(int command) {
if (command == 0) {
System.out.println(name + " walks.");
} else if (command == 1) {
System.out.println(name + " stops.");
} else if (command == 2) {
System.out.println(name + " jumps.");
} else {
throw new IllegalArgumentException("Command error. command = " + command);
}
}

public static void main(String[] args) {
Robot robot = new Robot("Andrew");
robot.order(0);
robot.order(1);
robot.order(2);
}

}


상수로 해결해보자.

public class Robot {
private static final int COMMAND_WALK = 0;
private static final int COMMAND_STOP = 1;
private static final int COMMAND_JUMP = 2;

private final String name;

public Robot(String name) {
this.name = name;
}

public void order(int command) {
if (command == COMMAND_WALK) {
System.out.println(name + " walks.");
} else if (command == COMMAND_STOP) {
System.out.println(name + " stops.");
} else if (command == COMMAND_JUMP) {
System.out.println(name + " jumps.");
} else {
throw new IllegalArgumentException("Command error. command = " + command);
}
}

public static void main(String[] args) {
Robot robot = new Robot("Andrew");
robot.order(COMMAND_WALK);
robot.order(COMMAND_STOP);
robot.order(COMMAND_JUMP);
}
}

Enum으로 해결해보자.

public class Robot {
private enum Command {
WALK, STOP, JUMP
}
private final String name;

public Robot(String name) {
this.name = name;
}

public void order(Command command) {
if (command == Command.WALK) {
System.out.println(name + " walks.");
} else if (command == Command.STOP) {
System.out.println(name + " stops.");
} else if (command == Command.JUMP) {
System.out.println(name + " jumps.");
} else {
throw new IllegalArgumentException("Command error. command = " + command);
}
}

public static void main(String[] args) {
Robot robot = new Robot("Andrew");
robot.order(Command.WALK);
robot.order(Command.STOP);
robot.order(Command.JUMP);
}
}


'Methdology > Refactoring' 카테고리의 다른 글

Feature Envy - 기능에 대한 욕심  (0) 2015.06.05
Comments