Clean Code 5. 형식

3 minute read

목차

형식을 맞추는 목적

  • 코드 형식은 의사소통의 일환이고, 의사소통은 전문 개발자의 일차적인 의무다.
  • 원래 코드는 사라질지라도 개발자의 스타일과 규율은 사라지지 않는다.

적절한 행 길이를 유지하라

  • 일반적으로 큰 파일보다 작은 파일이 이해하기 쉽다.
  • 신문 기사처럼 작성하라.
    • 이름은 간단하면서 설명이 가능하게 짓는다.
    • 소스 파일 첫 부분은 고차원 개념과 알고리즘을 설명한다.
    • 아래로 내려갈수록 의도를 세세하게 묘사한다.
    • 마지막은 가장 저차원 함수와 세부이 나오게 한다.
  • 개념은 빈 행으로 분리하라.
    • 각 행은 수식이나 절을 나타내고, 일련의 행 묶음은 완결된 생각 하나를 표현한다.
    • 생각 사이는 빈 행을 넣어 분리해야 마땅하다.
    • 빈 행이 없다면 가독성이 현저하게 떨어진다.
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();
  }
}

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();
  }
}
  • 세로 밀집도
    • 서로 밀접한 코드 행은 세로로 가까이 놓아야 한다.
  • 수직 거리
    • 연관성이 깊은 두 개념이 멀리 떨어져 있으면 코드를 읽는 사람이 소스 파일과 클래스를 여기저기 뒤지게 된다.
    • 변수 선언
      • 변수는 사용하는 위치에 최대한 가까이 선언한다.
    • 인스턴스 변수
      • 인스턴스 변수는 클래스 맨 처음에 선언한다.
      • 변수 간에 세로로 거리를 두지 않는다.
    • 종속 함수
      • 한 함수가 다른 함수를 호출한다면 두 함수는 세로로 가까이 배치한다.
      • 가능하면 호출하는 함수를 호출되는 함수보다 먼저 배치한다.
    • 개념적 유사성
      • 개념적 친화도가 높을수록 코드를 가까이 배치한다.
      • 친화도가 높은 요인 : 한 함수가 다른 함수 호출, 변수와 그 변수를 사용하는 함수, 비슷한 동작을 수행하는 함수
    • 세로 순서
      • 일반적으로 함수 호출 종속성은 아래 방향을 유지한다.
      • 호출되는 함수를 호출하는 함수보다 나중에 배치한다.

가로 형식 맞추기

  • 일반적으로 짧은 행이 바람직하다.
  • 가로 공백과 밀집도
    • 가로로는 공백을 사용해 밀접한 개념과 느슨한 개념을 표현한다.
    • 할당 연산자를 강조한 앞뒤 공백
    • 함수와 인수는 밀접하므로 공백 X
    • 괄호 안 인수 별개이므로 공백으로 분리
private void measureLine(String line) {
  lineCount++;
  int lineSize = line.length();
  totalChars += lineSize;
  lineWidthHistogram.addLine(lineSize, lineCount);
  recordWidestLine(lineSize);
}
  • 가로 정렬
    • 코드가 엉뚱한 부분을 강조하여 진짜 의도가 가려질 수 있다.
public class FitNesseExpediter implements ResponseSender
{
  private   Socket          socket;
  private   InputStream     input;
  private   OutputStream    output;
  private   Request         request;
  private   Response        response;
  private   FitNesseContext context;
  protected long            requestParsingTimeLimit;
  private   long            requestProgress;
  private   long            requestParsingDeadline;
  private   boolean         hasError;

  public FitNesseExpediter(Socket s, FitNesseContext context) throws Exception
  {
    this.context =            context;
    socket =                  s;
    input =                   s.getInputStream();
    output =                  s.getOutputStream();
    requestParsingTimeLimit = 10000;
  }
}
  • 들여쓰기
    • 범위로 이뤄진 계층을 표현하기 위해 코드를 들여쓴다.
    • 들여쓰기를 통해 구조가 한눈에 들어오므로 범위의 이동이 쉬워진다.
public class FitNesseServer implements SocketServer { private FitNesseContext context; public FitNesseServer(FitNesseContext context) { this.context = context; } public void serve(Socket s) { serve(s, 10000); } public void serve(Socket s, long requestTimeout) { try { FitNesseExpediter sender = new FitNesseExpediter(s, context); sender.start(); } catch (Exception e) { e.printStackTrace(); } } }

public class FitNesseServer implements SocketServer {
  private FitNesseContext context;
  public FitNesseServer(FitNesseContext context) {
    this.context = context;
  }
  
  public void serve(Socket s) {
    serve(s, 10000);
  }
  
  public void serve(Socket s, long requestTimeout) {
    try {
      FitNesseExpediter sender = new FitNesseExpediter(s, context);
      sender.setRequestParsingTimeLimit(requestTimeout);
      sender.start();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}
  • 들여쓰기 무시하기
    • 짧은 함수에서 들여쓰기 규칙을 무시하고 싶은 유혹을 참아야 한다.
public class CommentWidget extends TextWidget
{
  public static final String REGEXP = "^#[^\r\n]*(?:(?:\r\n)|\n|\r)?";
  
  public CommentWidget(ParentWidget parent, String text) { super(parent, text); }
  public String render() throws Exception { return ""; }
}

public class CommentWidget extends TextWidget
{
  public static final String REGEXP = "^#[^\r\n]*(?:(?:\r\n)|\n|\r)?";
  
  public CommentWidget(ParentWidget parent, String text) {
    super(parent, text); 
  }
  
  public String render() throws Exception { 
    return ""; 
  }
}

팀 규칙

  • 팀은 한가지 규칙에 합의해야 하고, 모든 팀원은 그 규칙을 따라야 한다.
  • 좋은 소프트웨어 시스템은 읽기 쉬운 문서로 이뤄지므로 소프트웨어는 일관적인 스타일을 보여야 한다.

과제

Leave a comment