나의 베스트 프랙티스 – 일반

1. 주석 – 저주이자 축복

좋은 주석은 하나의 예술입니다. 신중하게 쓰면 선물이 되지만, 헛수고로 끝나는 일도 많습니다.

자기 문서화 코드(self-documenting code)가 “주석을 쓰지 않는다”는 뜻은 아닙니다. 어떻게 동작하는지는 가능한 한 코드 스스로 드러내고, 주석으로는 왜 그렇게 하는지, 명확하지 않은 전제 조건, 그리고 API의 계약을 보충합니다.

아래에 자기 문서화 코드의 사례와 좋은 주석, 나쁜 주석의 예를 몇 가지 소개합니다.

자주 듣는 반론은 주석이 금방 낡는다는 것입니다. 하지만 이 문제는 변수 이름과 메서드 이름에도 똑같이 해당됩니다!

아야 – 이건 절대 하지 마세요:

int age = 32; // set the value of the age integer to 32

자기 문서화: 변수에 의미 있는 이름만 붙여도 반은 해결된다

나쁜 예:

var dateTime = DateTimeUtil.getNow();

좋은 예:

var now = DateTimeUtil.getNow();

또 다른 예:

나쁜 예:

User user = this.getBruce();

나쁜 예:

// testing user without permission
User user = this.getBruce();

좋은 예:

User userWithoutPermission = this.getBruce();

자기 문서화: 메서드에 의미 있는 이름 붙이기

나쁜 예:

public String sanitizeInput(String input) {
    // replace underscore with spaces
    return input.replaceAll("_", " ");
}

좋은 예:

public String replaceUnderscoreWithSpaces(String input) {
    return input.replaceAll("_", " ");
}

자기 문서화: private 메서드

나쁜 예: 읽는 사람이 검증, 계산, 비즈니스 규칙을 한꺼번에 해독해야 합니다.

public Invoice createInvoice(Order order, Customer customer) {
    if (order.items().isEmpty()) {
        throw new IllegalArgumentException("Order needs at least one item");
    }

    BigDecimal subtotal = order.items().stream()
            .map(item -> item.unitPrice().multiply(BigDecimal.valueOf(item.quantity())))
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    BigDecimal discount = customer.isPremium()
            ? subtotal.multiply(new BigDecimal("0.10"))
            : BigDecimal.ZERO;

    return new Invoice(order.id(), subtotal, discount, subtotal.subtract(discount));
}

좋은 예: public 메서드가 전체 흐름을 이야기합니다. 상태가 없는(stateless) private 메서드들이 각각의 의도에 이름을 붙이고, 의존 관계를 매개변수와 반환값으로 드러냅니다.

public Invoice createInvoice(Order order, Customer customer) {
    requireItems(order);
    BigDecimal subtotal = calculateSubtotal(order.items());
    BigDecimal discount = loyaltyDiscountFor(customer, subtotal);

    return invoiceFor(order, subtotal, discount);
}

private static void requireItems(Order order) {
    if (order.items().isEmpty()) {
        throw new IllegalArgumentException("Order needs at least one item");
    }
}

private static BigDecimal calculateSubtotal(List<OrderItem> items) {
    return items.stream()
            .map(item -> item.unitPrice().multiply(BigDecimal.valueOf(item.quantity())))
            .reduce(BigDecimal.ZERO, BigDecimal::add);
}

private static BigDecimal loyaltyDiscountFor(Customer customer, BigDecimal subtotal) {
    return customer.isPremium()
            ? subtotal.multiply(new BigDecimal("0.10"))
            : BigDecimal.ZERO;
}

private static Invoice invoiceFor(
        Order order,
        BigDecimal subtotal,
        BigDecimal discount
) {
    return new Invoice(order.id(), subtotal, discount, subtotal.subtract(discount));
}

모든 줄에 메서드가 따로 필요한 것은 아닙니다. 추출하는 것은 하나로 묶인 생각, 그것도 정확한 이름을 붙일 수 있는 생각입니다. processData()나 handleStuff() 같은 이름으로는 얻는 것이 없습니다.

경험칙: 무엇이 일어나는지가 아니라 왜 일어나는지를 주석으로 쓴다

여기서 무엇이 일어나는지는 분명합니다:

public Duration retryDelay(int retryCount) {
    long seconds = Math.min(1L << retryCount, 60);
    return Duration.ofSeconds(seconds);
}

그런데 왜 이렇게 할까요?

더 나은 예:

public Duration retryDelay(int retryCount) {
    // Cap the delay so an outage never blocks queued jobs for more than one minute.
    long seconds = Math.min(1L << retryCount, 60);
    return Duration.ofSeconds(seconds);
}

실무에서 가져온 예를 하나 더 보겠습니다. Ajax 로딩 스피너를 보이고 숨기는 메서드인데, 메서드가 네 개나 있습니다. 왜 그런지는 언뜻 봐서는 잘 알 수 없습니다:

function showAjaxLoader() {
    $('.layout-ajax-loader').children().first().show();
}

function hideAjaxLoader() {
    $('.layout-ajax-loader').children().first().hide();
}

function suppressAjaxLoader() {
    getOnlyElementByClassOrNull('layout-ajax-loader').style.display = 'none';
}

function releaseAjaxLoader() {
    getOnlyElementByClassOrNull('layout-ajax-loader').style.display = '';
}

메서드들이 모두 매우 비슷해 보이고, 어떻게든 CSS로 표시 여부를 바꾸는 것 같습니다. 짧은 주석 하나만 있으면 각각의 용도가 바로 드러납니다:

showAjaxLoader: function() {
    $('.layout-ajax-loader').children().first().show();
},

hideAjaxLoader: function() {
    $('.layout-ajax-loader').children().first().hide();
},

// take the control from primefaces and don't allow the spinner to show, no matter what
suppressAjaxLoader: function() {
    getOnlyElementByClassOrNull('layout-ajax-loader').style.display = 'none';
},

// reset the state after hiding, to give the control back to primefaces
releaseAjaxLoader: function() {
    getOnlyElementByClassOrNull('layout-ajax-loader').style.display = '';
},

또 다른 예:

나쁜 예:

/**
 * Sets the tool tip text.
 *
 * @param text  the text of the tool tip
 */
public void setToolTipText(String text) {}

좋은 예:

/**
 * Registers the text to display in a tool tip. The text
 * displays when the cursor lingers over the component.
 *
 * @param text  the string to display. If the text is null,
 *              the tool tip is turned off for this component.
 */
public void setToolTipText(String text) {}

2021-06-21 워크숍에서 나온 논의: 개발자 모두가 동의한 의견은, Javadoc은 기본적으로 피해야 한다는 것이었습니다(매개변수 지옥, 금방 낡음, 유지보수가 번거로움). Javadoc은 매개변수에 정말로 자세한 설명이 필요하거나, 그렇지 않으면 길고 긴 메서드를 끝까지 읽어야 하는 경우에만 쓰는 것이 좋습니다.

경험칙의 예외: 무엇이 일어나는지를 주석으로 쓴다 – 여기서는 그게 현명하다

주석이 없으면 코드가 분명하지 않아서, 주석이 가독성을 크게 높여 주는 경우입니다:

let isAlwaysAllowedKey = (
    e.which === 8  || /* BACKSPACE */
    e.which === 35 || /* END */
    e.which === 36 || /* HOME */
    e.which === 37 || /* LEFT */
    e.which === 38 || /* UP */
    e.which === 39 || /* RIGHT*/
    e.which === 40 || /* DOWN */
    e.which === 46 || /* DEL*/
    e.ctrlKey === true && e.which === 65 || /* CTRL + A */
    e.ctrlKey === true && e.which === 88 || /* CTRL + X */
    e.ctrlKey === true && e.which === 67 || /* CTRL + C */
    e.ctrlKey === true && e.which === 90   /* CTRL + Z */
)

주석 – Linux 커널 코드 속 욕설

끝으로 Linux 커널에 얽힌 재미있는 이야기 하나. 소스 코드에 들어 있는 욕설의 개수입니다:

https://www.vidarholen.net/contents/wordcount/#fuck*,shit*,damn*,idiot*,retard*

즐겁게 주석을 쓰세요!

2. 큰 처리 루틴 안의 private 메서드는 위험하다

주의! 오늘날의 객체 지향 세계에는 private 메서드가 언제나 많습니다. 보통은 문제가 되지 않습니다. 문제가 되는 것은 이런 메서드가 필드, 즉 상태(state)에 접근하면서 큰 루틴 안에 있을 때입니다. 이런 하위 메서드는 private이면서 상태가 없어야 합니다. 그렇지 않으면 단독으로 호출되었을 때 말썽을 일으키기 쉽습니다. 개발자들은 언젠가 그 하위 메서드를 호출하고 싶어지기 마련입니다. 잘못된 상태는 버그의 주요 원인 중 하나입니다. 이와 관련해 John Carmack(id Software, Doom)의 발언을 다룬 흥미로운 글이 있습니다. 코드가 매우 안정적이어야 하는 분야(예: 우주 비행)에서는 서브루틴을 금지하는 경우가 많고, 그 덕분에 코드가 더 결정적(deterministic)이 된다는 내용입니다: http://number-none.com/blow/john_carmack_on_inlined_code.html

이 이야기는 상태가 없는 것이 일반적인 현대 Java/Spring 세계에 그대로 들어맞지는 않지만, 그래도 생각해 볼 거리로는 충분합니다.