개요
독자들에게 주고 싶은 인상
- 코드가 깔끔
- 일관적
- 꼼꼼하다고 감탄
- 질서 정연하다고 탄복
- 모듈을 읽으며 두 눈이 휘둥그레 놀람
- 전문가가 짰다는 인상 심어줌
프로그래머라면 형식을 깔끔하게 맞춰 코드를 짜야 한다.
코드 형식을 맞추기 위한 간단한 규칙을 정하고 그 규칙을 착실히 따라야 한다.
팀으로 합의해 규칙을 정하고 모두가 그 규칙을 따라야 한다.
필요하다면 규칙을 자동으로 적용하는 도구를 활용한다.
형식을 맞추는 목적
코드 형식은 중요하다.
너무나 중요해서 무시하기 어렵고 너무나 중요해서 융통성 없이 맹목적으로 따르면 안 된다.
코드 형식은 의사소통의 일환이고 의사소통은 전문 개발자의 일차적 의무다.
오늘 구현한 기능이 다음 버전에서 바뀔 확률은 아주 높다.
그런데 오늘 구현한 코드의 가독성은 앞으로 바뀔 코드의 품질에 지대한 영향을 미친다.
적절한 행 길이를 유지하라
세로 길이부터 살펴보자
대다수 자바 소스 파일은 500줄을 넘지 않고 200정 정도로 이루어져 있어 커다란 시스템을 구축하는데 문제없다.
신문 기사처럼 작성하라
아주 좋은 신문기사를 떠올려보라.
- 눈에 띄는 표제
- 전체 기사 내용을 요약한 첫 문단
- 쭉 읽으며 내려가면서 나오는 세세한 사실
- 날짜, 이름, 발언, 주장, 기타 세부사항
소스파일도 신문기사와 비슷하게 작성한다.
- 이름은 간단하면서도 설명이 가능하게 짓는다.
- 이름만 보고도 올바른 모듈을 살펴보고 있는지 아닌지를 판단할 정도로 신경 써서 짓는다.
- 소스파일 첫 부분은 고차원 개념과 알고리즘을 설명한다.
- 아래로 내려갈수록 의도를 세세하게 묘사한다.
- 마지막에는 가장 저차원 함수와 세부 내역이 나온다.
개념은 빈 행으로 분리하라
빈 행은 새로운 개념을 시작한다는 시각적 단서다.
아래는 행을 넣지 않은 코드인데 보기 어려운 것을 알 수 있다.
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();
}
}
반대로 아래는 행을 넣은 코드인데 가독성이 높은 것을 알 수 있다.
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();
}
}
세로 밀집도
세로 밀집도는 연관성을 의미한다.
서로 밀접한 코드 행은 세로로 가까이 놓여야 한다는 뜻이다.
아래 코드는 의미 없는 주석으로 두 변수를 떨어뜨려 놓았다.
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);
}
}
수직거리
함수의 연관 관계와 동작 방식을 이해하려고 이 함수 저 함수를 오가며 소스 파일을 위아래로 뒤지는 등 고생한 경험이 있을 것이다.
서로 밀접한 개념은 세로로 가까이 둬야 한다.
그리고 타당한 근거가 없다면 서로 밀접한 개념은 한 파일에 둬야 한다.
이것이 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.getTests()) {
TestRunner tr = m_runnerFactory.newTestRunner(this, test);
tr.addListener(m_textReporter);
m_testRunners.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);
}
}
...
인스턴스 변수
인스턴스 변수는 클래스 맨 처음에 선언한다.
변수 간에 세로로 거리를 두지 않는다.
잘 설계한 클래스는 클래스의 많은 메서드가 인스턴스 변수에 사용하기 때문이다.
인스턴스 변수를 선언하는 위치는 아직도 논쟁이 분분하다.
일반적으로 C++에서는 모든 인스턴스 변수를 클래스 마지막에 선언한다는 소위 가위 규칙(scissors rule)을 적용한다.
하지만 JAVA에서는 보통 클래스 맨 처음에 인스턴스 변수를 선언한다.
어느 쪽 잘 알려진 위치에 인스턴스 변수를 모은다는 사실이 중요하다.
변수 선언을 어디서 찾을지 모두가 알고 있어야 한다.
아래 코드에서 변수를 잘 찾을 수 있을지 보자.
public class TestSuite implements Test {
static public Test createTest(Class<? extends TestCase> theClass, String name) {
...
}
public static Constructor<? extends TestCase> getTestConstructor(Class<? extends TestCase> theClass) throws NoSuchMethodException {
...
}
public static Test warning(final String message) {
...
}
private static String exceptionToString(Throwable t) {
...
}
private String fName;
private Vector<Test> fTests= new Vector<Test>(10);
public TestSuite() { }
public TestSuite(final Class<? extends TestCase> theClass) {
...
}
public TestSuite(Class<? extends TestCase> theClass, String name) {
...
}
...
}
종속함수
한 함수가 다른 함수를 호출한다면 두 함수는 세로로 가까이 배치한다.
또한 가능하다면 호출하는 함수를 호출되는 함수보다 먼저 배치한다.
아래 코드는 상수를 적절한 수준에 두는 좋은 예제다.
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, FitNesseContext context) throws Exception {
WikiPagePath path = PathParser.parse(resource);
crawler = context.root.getPageCrawler();
crawler.setDeadEndStrategy(new VirtualEnabledPageCrawler());
page = crawler.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);
SimpleResponse 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);
}
}
...
세로 순서
일반적으로 함수 호출 종속성은 아래 방향으로 유지한다.
다시 말해, 호출되는 함수를 호출하는 함수보다 나중에 배치한다.
그러면 소스 코드 모듈이 고차원에서 저차원으로 자연스럽게 내려간다.
신문기사와 마찬가지로 가장 중요한 개념을 가장 먼저 표현한다.
가장 중요한 개념을 표현할 때는 세세한 사항을 최대한 배제한다.
세세한 사항은 가장 마지막에 표현한다.
그렇다면 소스파일에서 첫 함수 몇 개만 읽어도 개념을 파악하기 쉬워진다.
가로 형식 맞추기
한 행은 가로가 얼마나 길어야 적당할까?
결과가 놀랍게도 규칙적인데 특히 45자 근처가 그렇다.
프로그래머는 명백하게 짧은 행을 선호한다.
예전에는 오른쪽으로 스크롤 할 필요가 절대로 없게 코드를 짰다.
요즘은 모니터가 아주 크고, 젊은 프로그래머들은 글꼴 크기를 왕창 줄여 200자까지도 한 화면에 들어간다.
그러나 가급적으로 그러지 말고 120자 정도로 행 길이를 제한한다.
가로 공백과 밀집도
가로로는 공백을 사용해 밀접한 개념과 느슨한 개념을 표현한다.
아래 코드를 봐보자
private void measureLine(String line) {
lineCount++;
int lineSize = line.length();
totalChars += lineSize;
lineWithHistogram.addLine(lineSize, lineCount);
recordWidestLine(lineSize);
}
할당 연산자를 강조하려고 앞뒤에 공백을 줬다.
할당문은 왼쪽 요소와 오른쪽 요소가 분명히 나뉜다.
공백을 넣으면 두 가지 주요 요소가 확실히 나뉜다는 사실이 더욱 분명해진다.
반면, 함수 이름과 이어지는 골화 사이에는 공백을 넣지 않았다.
함수와 인수는 서로 밀접하기 때문이다. 공백을 넣으면 한 개념이 아니라 별개로 보인다.
함수를 호출하는 코드에서 괄호 안 인수는 공백으로 분리했다.
쉼표를 강조해 인수가 별개라는 사실을 보여주기 위해서다.
가로 정렬
아래 코드가 보기는 좋을지라도 엉뚱한 부분을 강조해 진짜 의도가 가려진다.
특히 일일이 띄어쓰기하고 번거롭다.
public class FitNesseExpediter implements ResponseSender {
private Socket socket;
private InputStream input;
private OutputStream output;
private Reques request;
private Response response;
private FitNesseContex context;
protected long requestParsingTimeLimit;
private long requestProgress;
private long requestParsingDeadline;
private boolean hasError;
...
}
오히려 아래 코드가 더 깔끔하다
public class FitNesseExpediter implements ResponseSender {
private Socket socket;
private InputStream input;
private OutputStream output;
private Reques request;
private Response response;
private FitNesseContex context;
protected long requestParsingTimeLimit;
private long requestProgress;
private long requestParsingDeadline;
private boolean hasError;
...
}
들여쓰기
범위로 이뤄진 계층을 표현하기 위해 우리는 코드를 들여 쓴다.
프로그래머는 이런 들여쓰기 체계에 크게 의존한다.
왼쪽으로 코드를 맞춰 코드가 속하는 범위를 시각적으로 표현한다.
그러면 이 범위에서 저 범위로 재빨리 이동하기 쉬워진다.
현재 상황과 무관한 if 문/while 문 코드를 일일이 살펴볼 필요가 없다.
소스파일 왼쪽을 훑으면서 새 메서드, 새 변수, 새 클래스도 찾는다.
들여 쓰기가 없다면 인간이 코드를 읽기란 거의 불가능하다.
아래 두 코드는 문법과 의미가 동일하다.
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 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();
}
}
}
그러나 들여 쓰기 한 파일은 구조가 한눈에 들어온다.
반면, 들여쓰기 하지 않은 코드는 열심히 분석하지 않는 한 거의 불가능하다.
들여쓰기 무시하기
때로는 간단한 if문, 짧은 while문, 짧은 함수에서 들여쓰기 규칙을 무시하고픈 유혹이 생긴다.
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 "";
}
}
가짜 범위
때로는 빈 while문이나 for문을 접한다.
그러나 이런 구조는 피하자.
while (dis.read(buf, 0, readBufferSize) != -1)
;
팀 규칙
프로그래머라면 각자 선호하는 규칙이 있다.
하지만 팀에 속한다면 자신이 선호해야 할 규칙은 바로 팀 규칙이다.
팀은 한 가지 규칙에 합의해야 한다.
그리고 모든 팀원들은 그 규칙을 따라야 한다.
그래야 소프트웨어가 일관적인 스타일을 보인다.
좋은 소프트웨어 시스템은 읽기 쉬운 문서로 이뤄진다는 사실을 기억하기 바란다.
스타일은 일관적이고 매끄러워야 한다.
한 소스 파일에서 봤던 형식이 다른 소스 파일에도 쓰이리라는 신뢰감을 독자에게 줘야 한다.
밥 아저씨의 형식 규칙
구현 표준 문서가 되는 예시니까 참고하시면 된다.
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)
measureLine(line);
}
private void measureLine(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() {
Integer[] sortedWidths = getSortedWidths();
int cumulativeLineCount = 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 = lineWidthHistogram.getWidths();
Integer[] sortedWidths = (widths.toArray(new Integer[0]));
Arrays.sort(sortedWidths);
return sortedWidths;
}
}
글쓴이의 생각
코드가 양옆으로 너무 길면 해석하기 어려울 때가 많다.
특히 대학교 과제했을 때 짰던 코드가 기억하는데 그때는 정리가 안돼서 지금 생각하면 아찔하다.
만약 클래스가 한 가지 기능하도록만 짰더라면 좀 더 보기 편했을 텐데 라고 생각한다.
지금도 일하면서 클래스를 엉망으로 짤 때가 있지만 이 책의 내용을 보고 좀 더 잘 정리해서 짜야 될 필요를 느꼈다.
'클린코드(CleanCode) 독후감' 카테고리의 다른 글
[클린코드(CleanCode)] 7장 오류 처리 (6) | 2025.01.13 |
---|---|
[클린코드(CleanCode)] 6장 객체와 자료 구조 (5) | 2025.01.10 |
[클린코드(CleanCode)] 4장 주석 (4) | 2025.01.09 |
[클린코드(CleanCode)] 3장 함수 (2) | 2025.01.09 |
[클린코드(CleanCode)] 2장 의미있는 이름 (4) | 2025.01.08 |