Indentation and Code Style

이정훈·2024년 7월 31일

들여쓰기는 시각적으로 관련있는 코드들을 모아두기 위해 사용됩니다.
이는 읽기 쉽고 이해하기 쉬운 코드 구조를 만들어 냅니다.
코드 스타일은 코드의 형태와 구조를 어떻게 할지에 대한 가이드라인입니다.
일관성있는 들여쓰기와 코드 스타일은 읽기 쉽고 이해하기 쉬운 코드를 만들 수 있도록 도와줍니다.

이에 대해 자세히 알아 봅시다.

Formatting

Vertical Formatting

클린 코드를 작성할 때 가장 유명한 말은 코드를 읽는 과정이 신문을 읽는 과정과 같아야 한다는 것입니다.
파일의 타이틀이나 키 컨셉 그리고 알고리즘은 코드의 상단에 위치하게 만들어 쉽게 찾을 수 있게 만들어야 한다는 것입니다.

Vertical Density

Vertical Density는 코드 사이의 공백을 적절히 이용하여 서로 관련있는 것들끼리 모아줘야 한다는 것입니다.
아래는 Vertical Density가 지켜지지 않은 예시입니다.

package fitnesse.wikitext.widgets;
import java.util.regex.*;
public class BoldWidget extends ParentWidget {
    public static final String REGEXP = "'''.+?'''";
    private static final Pattern pattern = Pattern.compile("'''(.+?)'''", Pattern.MULTILINE + Pattern.DOTALL);
    public BoldWidget(ParentWidget parent, String text) throws Exception {
        super(parent);
        Matcher match = pattern.matcher(text);
        match.find();
        addChildWidgets(match.group(1));}
    public String render() throws Exception {
        StringBuffer html = new StringBuffer("<b>");
        /**
        * Adds the HTML closing tag
        */
        html.append(childHtml()).append("</b>");
        return html.toString();
    }
}

이번에는 Vertical Density가 지켜진 예시를 보겠습니다.

package fitnesse.wikitext.widgets;

import java.util.regex.*;

public class BoldWidget extends ParentWidget {
    public static final String REGEXP = "'''.+?'''";
    private static final Pattern pattern = Pattern.compile("'''(.+?)'''",Pattern.MULTILINE + Pattern.DOTALL);

    public BoldWidget(ParentWidget parent, String text) throws Exception {
        super(parent);
        Matcher match = pattern.matcher(text);
        match.find();
        addChildWidgets(match.group(1));
    }

    public String render() throws Exception {
        StringBuffer html = new StringBuffer("<b>");
        html.append(childHtml()).append("</b>");
        return html.toString();
    }
}

Vertical Distance

Vertical Distance는 변수의 선언은 가능한 이러한 변수들이 사용되는 곳에서 가까운 위치에서 해야 한다는 것입니다.

Vertical Ordering

Vertical Ordering는 의존 관계를 보여줘야 한다는 것을 의미합니다.
만약 높은 수준의 함수가 다른 하위 수준의 함수를 호출한다면 이 함수는 맨 위에 위치하고 다른 하위 수준 함수는 아래에 위치해야 합니다.

Horizontal Formatting

한 줄에 몇개의 글자가 들어가는 것이 적절한지 연구된 적이 있습니다.
1890년에 80자라고 알려져 있었습니다.
최근에 와서는 모니터도 커지고 IDE도 발전해 160까지도 괜찮다는 말도 있습니다.
이는 엄격한 규칙이 아니라 적절한 선에서 한 줄에 몇자가 들어갈지 결정하는 것이 좋습니다.

Horizontal Openness and Density

Vertical Density와 마찬가지로 Horizontal Openness와 Density를 통해 서로 관련있는 것과 서로 관련없는 것들을 구별해줘야 합니다.
아래는 Horizontal Openness and Density를 지킨 예시입니다.

public class CountCharsInString {
    public static void main(String[] args) {
        String exampleString = "This is just a sample string";
        long totalCharacters = exampleString.chars().filter(ch -> ch != ' ').count();
        System.out.println("There are total " + totalCharacters + " characters in exampleString");
    }
}

Horizontal Alignment and Indentation

Horizontal Alignment에서 완벽한 정렬을 목표로 하면 안됩니다. 오히려 변수의 타입이나 할당 연산자를 쉽게 볼 수 있도록 하는 것이 중요합니다.
아래와 같이 하면 안된다는 것입니다.

public FitNesseExpediter(Socket s,
                         FitNesseContext context) throws Exception
{
    this.context =            context;
    socket =                  s;
    input =                   s.getInputStream();
    output =                  s.getOutputStream();
    requestParsingTimeLimit = 10000;
}

Horizontal Indentation은 코드의 종속성과 범위를 시각적으로 표시하는 방법이기 때문에 올바르게 사용되어야 합니다.
아래와 같이 하면 안된다는 것입니다.

public class Factorial{	public static void main(String[] args){	final int NUM_FACTS = 100; for(int i = 0; i < NUM_FACTS; i++) System.out.println( i + "! is " + factorial(i));}
public static int factorial(int n){ int result = 1;for(int i = 2; i <= n; i++) result *= i; return result;}}
profile
기록으로 흔적을 남깁니다.

0개의 댓글