책 - 요약 정리/클린 코드

2장. 의미 있는 이름

kimjingyu 2023. 8. 31. 22:41
728x90

의도를 분명히 밝혀라

코드 맥락이 코드 자체에 명시적으로 드러날 수 있게 하자

  • 다음 코드는 코드가 하는 일을 짐작하기 어렵다.
private List<int[]> theList = new ArrayList<>();

public List<int[]> getThem() {
    List<int[]> list1 = new ArrayList<int[]>();
    for (int[] x : theList) {
        if (x[0] == 4) {
            list1.add(x);
        }
    }
    return list1;
}
  • 하지만 아래와 같이 단순히 이름만 고치면 함수가 하는 일을 이해하기 쉬워진다.
public static final int STATUS_VALUE = 0;
public static final int FLAGGED = 4;
private List<Cell> gameBoard = new ArrayList<>();

public List<Cell> getFlaggedCells() {
    List<Cell> flaggedCells = new ArrayList<Cell>();
    for (Cell cell : gameBoard) {
        if (cell.isFlagged()) {
            flaggedCells.add(cell);
        }
    }
    return flaggedCells;
}

public static class Cell {
    private int[] cell = new int[4];

    public boolean isFlagged() {
        return cell[STATUS_VALUE] == FLAGGED;
    }
}

메서드 이름

생성자를 중복정의(Overload) 할 때는 정적 팩토리 메서드를 사용한다. 이때 메서드는 인수를 설명하는 이름을 사용한다.

Complex fulcrumPoint = new Complex(23.0);

즉, 위 코드보다 아래 코드가 좋다.

Complex fulcrumPoint = Complex.FromRealNumber(23.0);

의미 있는 맥락을 추가하라

스스로 의미가 분명한 이름이 없지 않지만, 대다수의 이름은 그렇지 못하다. 그래서 클래스, 함수 이름을 넣어 맥락을 부여한다. 그리고 모든 방법이 실패하면 마지막 수단으로 접두어를 붙인다. 물론 클래스를 생성하면 더 좋다.

  • 다음은 맥락이 불분명한 변수를 가진 함수이다. 여기서는 함수를 끝까지 읽어보고 나서야 변수 세 개가 통계 추측 메시지에 사용된다는 사실이 드러난다. 즉, 독자가 맥락을 유추해야 한다.
private void printGuessStatistics(char candidate, int count) {
    String number;  // 숫자
    String verb;    // 동사
    String pluralModifier;  // 복수형 표현
    if (count == 0) {
        number = "no";
        verb = "are";
        pluralModifier = "s";
    } else if (count == 1) {
        number = "1";
        verb = "is";
        pluralModifier = "";
    } else {
        number = Integer.toString(count);
        verb = "are";
        pluralModifier = "s";
    }
    String guessMessage = String.format("There %s %s%s", verb, number, pluralModifier);
    System.out.println(guessMessage);
}
  • 세 변수를 함수 전반에서 사용하므로, 함수를 작은 조각으로 쪼개고자 클래스를 만든 후 세 변수를 클래스에 넣는다. 그러면 세 변수는 맥락이 분명해진다.
public class GuessStatisticsMessage {
    private String number;  // 숫자
    private String verb;    // 동사
    private String pluralModifier;  // 복수형 표현

    public String make(char candidate, int count) {
        createPluralDependentMessageParts(count);
        return String.format("There %s %s%s", verb, number, pluralModifier);
    }

    private void createPluralDependentMessageParts(int count) {
        if (count == 0) {
            thereAreNoLetters();
        } else if (count == 1) {
            thereIsOneLetter();
        } else {
            thereAreManyLetters(count);
        }
    }

    private void thereAreNoLetters() {
        number = "no";
        verb = "are";
        pluralModifier = "s";
    }

    private void thereIsOneLetter() {
        number = "1";
        verb = "is";
        pluralModifier = "";
    }

    private void thereAreManyLetters(int count) {
        number = Integer.toString(count);
        verb = "are";
        pluralModifier = "s";
    }
}
728x90