본문 바로가기

Book Review/Clean Code

클린코드 5장_형식 맞추기

5장 형식 맞추기

 

1. 형식을 맞추는 목적

  • 코드 형식은 의사소통의 일환이다

2. 적절한 행 길이를 유지하라

  • 500줄을 넘지 않고도 대부분 200줄 정도인 파일로도 커다란 시스템을 구축할 수 있는 사실이다.
  • 일반적으로 큰 파일보다 작은 파일이 이해하기 쉽다

3. 신문 기사처럼 작성하라

  • 소스 파일도 신문 기사와 비슷하게 작성한다. 이름은 간단하면서도 설명이 가능하게 짓는다.
  • 이름만 보고도 올바른 모듈을 살펴보고 있는지 아닌지를 판단할 정도로 신경 써서 짓는다.
  • 소스 파일 첫 부분은 고차원 개념과 알고리즘을 설명한다. 아래로 내려갈수록 의도를 세세하게 묘사한다. 마지막에는 가장 저차원 함수와 세부 내역이 나온다.

4. 개념은 빈 행으로 분리하라

  • 거의 모든 코드는 왼쪽에서 오른쪽으로 그리고 위에서 아래로 읽힌다. 각 행은 수식이나 절을 나타내고, 일련의 행 묶음은 완결된 생각 하나를 표현한다. 생각 사이는 빈 행을 넣어 분리해야 마땅하다
package fitnesses.wikitext.widgets;

import java.util.regex.*;

public class BoldWidget extedns 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);
		Mathcer match = pattern.matcher(text);
		match.fid();
		addChildWidgets(match.group(1));
	}

	public String render() throws Exception {
		StringBuffer html = new StringBuffer("<b>");
		html.append(childHtml()).append("</b>");
		return html.toString();
	}
}
  • 위 코드는 패키지 선언부, import 문, 각 함수 사이에 빈 행이 들어간다. 너무도 간단한 규칙이지만 코드의 세로 레이아웃에 심오한 영향을 미친다. 빈 행은 새로운 개념을 시작한다는 시각적 단서이다.
package fitnesses.wikitext.widgets;
import java.util.regex.*;
public class BoldWidget extedns 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);
		Mathcer match = pattern.matcher(text);
		match.fid();
		addChildWidgets(match.group(1));
	}
	public String render() throws Exception {
		StringBuffer html = new StringBuffer("<b>");
		html.append(childHtml()).append("</b>");
		return html.toString();
	}
}
  • 위 코드는 앞의 코드에서 빈 행을 빼버린 코드이다. 코드 가독성이 현저하게 떨어져 암호처럼 보인다.

5. 세로 밀집도

  • 줄바꿈이 개념을 분리한다면 세로 밀집도는 연관성을 의미한다. 즉, 서로 밀접한 코드 행은 세로로 가까이 놓여야 한다는 뜻이다.
public class ReporterConfig {
	/**
	* 리포터 리스너의 클래스 이름
	*/
	private String m_className;

	/**
	* 리포터 리스너의 속성
	*/
	private List<Property> m_properties = new ArrayList<Property>();
	public void addProperty(Property property) {
		m_properties.add(property):
	}
  • 위 코드보다 아래 코드가 훨씬 더 읽기 쉽다.
public class ReporterConfig {
	private String m_className;
	private List<Property> m_properties = new ArrayList<Property>();
	public void addProperty(Property property) {
		m_properties.add(property):
	}

6. 수직 거리

  • 서로 밀접한 개념은 세로로 가까이 둬야한다. 타당한 근거가 없다면 서로 밀접한 개념은 한 파일에 속해야 마땅하다. 이게 바로 protected 변수를 피해야 하는 이유 중 하나이다.
  • 같은 파일에 속할 정도로 밀접한 두 개념은 세로 거리로 연관성을 표현한다.
    • 여기서 연관성이란, 한 개념을 이해하는 데 다른 개념이 중요한 정도다.

변수선언

  • 변수는 사용하는 위치에 최대한 가까이 선언한다.
  • 우리가 만든 함수는 매우 짧으므로 지역 변수는 각 함수 맨 처음에 선언한다.
private static void readPreferences() {
	**InputStream is = null;**
	try {
		is = new FileInputStream(getPreferencesFile());
		setPreferences(new Properties(getPreferences());
		getPreferences().load(is);
	} catch (IOException e) {
	try{
		if (is != null)
			is.close();
	} catch (IOException e1) {
		}
	}
}
  • 루프를 제어하는 변수는 흔히 루프 문 내부에 선언한다.
public int countTestCases() {
	int count = 0;
	**for (Test each: tests)**
		count += each.countTestCases();
	return count;
}

아주 드물지만 다소 긴 함수에서 블록 상단이나 루프 직전에 변수를 선언하는 사례도 있다.

for (XmlTest test: m_suite.getTest()) {
	**TestRunner tr = m_runnerFactory.newTestRunner(this, test);**
	tr.addListenr(m_textReporter);
	m_testRuners.add(tr);

	invoker = tr.getInvoker();
	
	for (ITestNGMethod m: tr.getBeforeSuiteMethods()) {
		beforeSuiteMethods.put(m.getMethod(), m);
	}
	
	for (ITestNGMethod m: tr.getAfterSuiteMethods()) {
		afterSuiteMethods.put(m.getMethod(), m);
	}

인스턴스 변수

  • 인스턴스 변수는 클래스 맨 처음에 선언한다. 변수 간에 세로로 거리를 두지 않는다.

종속 변수

  • 한 함수가 다른 함수롤 호출한다면 두 함수는 세로로 가까이 배치한다. 또한 가능하다면 호출하는 함수를 호출되는 함수보다 먼저 배치한다.
public class WikiPageResponder implements SecureResponder {
	protected WikiPage page;
	protected PageData pageData;
	protected String pageTitle;
	protected Request request;
	protected PageCrawler crawler;

	public Response makeResponse(FitNesseContext context, Request request) throws Exception {
		String pageName = getPageNameOrDefault(request, "FrontPage");
		loadPage(pageName, context);
		if (page == null)
			return notFoundResponse(context, request);
		else
			return makePageResponse(context);
	}
	
	private String getPageNameOrDefault(Request request, String defaultPageName)
	{
		String pageName = request.getResource();
		if (StringUtil.isBlank(pageName))
			pageName = defaultPageName;
		return pageName;
	}

	protected void loadPage(String resource, FitNessesContext context) throws Exception {
		WikiPagePath path = PathParser.parse(resource);
		crawler = context.root.getPageCrawler();
		cralwer.setDeadEndStrategy(new VirtualEnabledPageCrawler());
		page = craler.getPage(context.root, path);
		if(page != null)
			pageData = page.getData();
		}

	private Response notFoundResponse(FitNesseContext context, Request request) throws Exception {
		return new NotFoundResponder().makeResponse(context, request);
	}

	private SimpleResponse makePageResponse(FitNesseContext context) throws Exception {
		pageTitle = PathParser.render(crawler.getFullPath(page));
		String html = makeHtml(context);

		SimpleRespose response = new SimpleResponse();
		response.setMaxAge(0);
		response.setContent(html);
		return response;
	}
  • 첫째 함수에서 가장 먼저 호출하는 함수가 바로 아래 정의된다. 다음으로 호출하는 함수는 그 아래에 정의된다.
  • 위 코드는 상수를 적절한 수준에 두는 좋은 예제이다.

개념적 유사성

  • 어떤 코드는 서로 끌어당긴다. 개념적인 친화도가 높기 때문이다.
  • 비슷한 동작을 수행하는 일군의 함수들은 친화도가 높다고 볼 수 있다.
  • 친화도가 높을수록 코드를 가까이 배치한다.
public class Assert {
	static public void assertTrue(String message, boolean condition) {
		if (!condition)
			fail(message);
	}

	static public void assertTrue(boolean condition) {
		assertTrue(null, condition);
	}

	static public void assertFalse(String message, boolean condition) {
		assertTrue(message, !condition);
	}
	
	static public void assertFalse(boolean condition) {
		assertFalse(null, condition);
	}
  • 위 함수들은 명명법이 똑같고 기본 기능이 유사하여 개념적인 친화도가 매우 높다.

세로 순서

  • 일반적으로 함수 호출 종속성은 아래 방향으로 유지한다. 다시 말해서 호출되는 함수를 호출하는 함수보다 나중에 배치한다.

7. 가로 형식 맞추기

  • 프로그래머는 명백하게 짧은 행을 선호한다.
  • 120자 정도의 행 길이가 좋다.

가로 공백과 밀집도

  • 가로로는 공백을 사용해 밀접한 개념과 느슨한 개념을 표현한다.
private void mesaureLine(String line) {
	lineCount++;
	int lineSize = line.length();
	totalChars += lineSize;
	lineWidthHistogram.addLine(lineSize, lineCount);
	recordWidestLine(lineSize);
}
  • 할당 연산자를 강조하기 위해 앞뒤에 공백을 줬다.
  • 함수 이름과 이어지는 괄호 사이에는 공백을 넣지 않는다.
public class Quadratic {
	public static double root1(double a, double b, double c) {
		double determinant = determinant(a, b, c);
		return (-b + Math.sqrt(determinant)) / (2*a);
	}
	
	public static double root2(int a, int b, int c) {
		double determinant = determinant(a, b, c);
		return (-b - Math.sqrt(determinant)) / (2*a);
	}
	private static double determinant(double a, double b, double c) {
		return b*b - 4*a*c;
	}
}
  • 연산자 우선순위를 강조하기 위해서도 공백을 사용한다.
  • 승수 사이에는 공백이 없다. 곱셈은 우선순위가 가장 높기 때문이다. 하지만, 항 사이에는 공백이 들어간다. 덧셈과 뺄셈은 우선순위가 곱셉보다 낮기 때문이다.
  • 하지만 IDE는 연산자 우선순위를 고려하지 못하므로, 수식에 똑같은 간격을 적용한다.

들여 쓰기

  • 범위로 이뤄진 계층을 표현하기 위해 우리는 코드를 들여쓴다. 들여쓰는 정도는 계층에서 코드가 자리잡은 수준에 비례한다.
    • 클래스 정의처럼 파일 수준인 문장은 들여쓰지 않고, 클래스 내 메서드는 클래스보다 한 수준 들여쓴다.
    • 메서드 코드는 메서드 선언보다 한 수준 들여쓴다.
    • 블록 코드는 블록을 포함하는 코드보다 한 수준 들여쓴다.
    • 들여쓰기를 한 파일은 구조가 한 눈에 들어오지만, 들여쓰기를 하지 않은 코드는 열심히 분석하지 않는 한 거의 불가해하다.

들여쓰기 무시하기

  • 때로는 간단한 if문, 짧은 while 문, 짧은 함수에서 들여쓰기 규칙을 무시하고픈 유혹이 생기는데 이럴 경우에는 들여쓰기를 하는게 낫다.
public class CommentWidget extends TextWidget
{
	public static final String REGEXP = "&##@#@!#!@#!@#!";
	
	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 = "&##@#@!#!@#!@#!";
	
	public CommentWidget(ParentWidget parent, String text){
		super(parent, text);
	}

	public String render() throws Exception {
		return ""; 
	}
}

가짜 범위

  • 떄로는 빈 while 문이나 for문을 접하는데, 가능한 한 피하려 애쓰지만 피하지 못할 때는 빈 블록을 올바로 들여쓰고 괄호로 감싼다. 세미클론(;)은 새 행에다 제대로 들여써서 넣어준다. 그렇게 하지 않으면 눈에 띄지 않는다.
while (dis.read(buf, 0, readBufferSize) != -1)
;

팀 규칙

프로그래머라면 각자 선호하는 규칙이 있지만, 팀에 속한다면 자신이 선호해야 할 규칙은 바로 팀 규칙이다.

  • 팀은 한 가지 규칙에 합의해야 한다, 그리고 모든 팀원은 그 규칙을 따라야 한다.
  • 저자가 FitNesses 프로젝트를 처음 시작했을 때, 팀과 마주 앉아 구현 스타일을 논의했다. 어디에 괄호를 넣을지, 들여쓰기는 몇자로 할지, 클래스와 변수와 메서드 이름은 어떻게 지을지 결정했다. 그리고 정한 규칙으로 IDE 코드 형식기를 설정한 후 계속 사용했다.
  • 좋은 소프트웨어 시스템은 읽기 쉬운 문서로 이뤄져야하고, 스타일은 일관적이고 매끄러워야 한다. 한 소스파일에서 봤던 형식이 다른 소스 파일에서도 쓴다는 신뢰감을 독자에게 줘야 한다.

밥 아저씨의 형식 규칙

public class CodeAnalyzer implements JavaFileAnalysis {
	private int lineCount;
	private int maxLineWidth;
	private int widestLineNumber;
	private LineWidthHistogram lineWidthHistogram;
	private int totalChars;

	public CodeAnalyzer() {
		lineWidthHistogram = new LineWidthHistogram();
	}

	public static List<File> findJavaFiles(File parentDirectory) {
		List<File> files = new ArrayList<File>();
		findJavaFiles(parentDirectory, files):
		return files;
	}

	private static void findJavaFiles(File parentDirectory, List<File> files) {
		for (File file: parentDirectory.listFiles()) {
			if (file.getName().endsWith(".java"))
				files.add(file);
			else if (file.isDirectory())
				findJavaFiles(file, files);
		}
	}

	public void analyzeFile(File javaFile) throws Exception {
		BufferedReader br = new BufferedReader(new FileReader(javaFile));
		String line;
		while ((line = br.readline()) != null)
			mesaureLine(line)
	}

	private void mesaureLine(String line) {
		lineCount++;
		int lineSize = line.length();
		totalChars += lineSize;
		lineWidthHistogram.addLine(lineSize, lineCount);
		recordWidestLine(lineSize);
	}

	private void recordWidestLine(int lineSize) {
		if (lineSize > maxLineWidth) {
			maxLineWidth = lineSize;
			widestLineNumber = lineCount;
		}
	}

	public int getLineCount() {
		return lineCount;
	}

	public int getMaxLineWidth() {
		return maxLineWidth;
	}

	public int getWidestLineNumber() {
		return widestLineNumber;
	}

	public LineWidthHistogram getLineWidthHistogram() {
		return LineWidthHistogram;
	}

	public double getMeanLineWidth() {
		return (double)totalChars/lineCount;
	}

	public int getMedianLineWidth() {
		return (double) totalChars/lineCount;
	}

	public int getMedianLineWIdth() {
		Integer[] sortedWidths = getSortedWidths();
		int cumlativeLineCount = 0;
		for (int width : sortedWidths) {
			cumulativeLineCount += lineCountForWidth(width);
			if (cumulativeLineCount > lineCount/2)
				return width;
		}
		throw new Error("Cannot get here");
	}

	private int lineCountForWidth(int width) {
		return lineWidthHistogram.getLinesforWidth(width).size();
	}

	private Integer[] getSortedWidths() {
		Set<Integer> widths = (widths.toArray(new Integer[0]));
		Integer[] sortedWidths = (widths.toArray(new Integer[0]));
		Arrays.sort(sortedWidths);
		return sortedWidths;
	}
}		

참고 자료

  • Clean Code 애자일 소프트웨어 장인 정신

'Book Review > Clean Code' 카테고리의 다른 글

클린코드 7장_오류 처리  (1) 2022.09.14
클린코드 6장_객체와 자료구조  (0) 2022.09.09
클린코드 4장_주석  (0) 2022.08.30
클린 코드 3장 정리 #1  (0) 2022.07.30
클린 코드 2장 정리 #2  (0) 2022.07.29