뚜껑을 열었을 때 독자들이 코드가 깔끔하고, 일관적이며, 꼼꼼하다고 감탄하면 좋겠다. 질서 정연하다고 탄복하면 좋겠다. 모듈을 읽으며 두 눈이 휘둥그래 놀라면 좋겠다. 전문가가 짰다는 인상을 심어주면 좋겠다. 그 대신에 술 취한 뱃 사람 한 무리가 짜놓은 듯 어수선해 보인다면 독자들은 프로젝ㅌ의 다른 측면도 똑같이 무성의한 태도로 처리했으리라 생각할 것이다.

프로그래머라면 형식을 깔끔하게 맞춰 코드를 짜야한다. 코드 형식을 맞추기 위한 간단한 규칙을 정하고 그 규칙을 착실히 따라야 한다. 팀으로 일한다면 팀이 합의해 규칙을 정하고 모두가 그 규칙을 따라야 한다. 필요하다면 규칙을 자동으로 적용하는 도구를 활용한다.


형식을 맞추는 목적

코드 형식은 중요하다. 코드 형식은 의사소통의 일환이다. 의사소통은 전문 개발자의 일차적인 의무다.

오늘 구현한 기능이 다음 버전에서 바뀔 확률은 아주 높다. 그런데 오늘 구현한 코드의 가독성은 앞으로 바뀔 코드의 품질에 지대한 영향을 미친다. 오랜시간이 지나 원래 코드의 흔적을 더 이상 찾아보기 어려울 정도로 코드가 바뀌어도 맨 처음 잡아놓은 구현 스타일과 가독성 수준은 유지보수 용이성과 확장성에 계속 영향을 미친다.


적절한 행 길이를 유지하라

반드시 지킬 엄격한 규칙은 아니지만 바람직한 규칙으로 삼으면 좋겠다. 일반적으로 큰 파일보다 작은 파일이 이해하기 쉽다.

신문 기사처럼 작성하라

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

개념은 빈 행으로 분리하라

각 행은 수식이나 절을 나타내고, 일련의 행 묶음은 완결된 생각 하나를 표현한다. 생각 사이는 빈 행을 넣어 분리해야 마땅하다.

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);
}

수직 거리

함수 연관 관계와 동작 방식을 이해하려고 이 함수에서 저 함수로 오가며 소스 파일을 위아래로 뒤지는 등 뺑뺑이를 돌았으나 결국은 미로 같은 코드 때문에 혼란만 생기는 경우가 있다.

서로 밀접한 개념은 세로로 가까이 둬야한다. 두 개념이 서로 다른 파일에 속한가면 규칙이 통하지 않지만 타당한 근거가 없다면 서로 밀접한 개념은 한 파일에 속해야 한다.

변수선언

변수는 사용하는 위치에 최대한 가까이 선언한다.

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);
 }
}
...

인스턴스 변수

인스턴스 변수는 클래스 맨 처음에 선언한다. 변수 간에 세로로 거리를 두지 않는다. 잘 설계한 클래스는 많은 클래스 메서드가 인스턴스 변수를 사용하기 때문이다.

인스턴스 변수는 맨 처음 또는 맨 아래 둘중 하나 이겠지만 잘 모은다는게 중요하다.

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);
 }
...

세로 순서

일반적으로 함수 종속성은 아래 방향으로 유지한다. 호출되는 함수를 호출하는 함수보다 나중에 배치한다. 그러면 소스 코드 모듈이 고차원에서 저차원르오 자연스럽게 내려간다.

가로 형식 맞추기

짧은 행이 바람직하다. 옛날 홀러리스가 내놓은 80자 제한은 다소 인위적이다.요즘은 모니터의 길이도 크고 하니 크게크게 만들어도 무방하다.

가로 공백과 밀집도

가로로는 공백을 사용해 밀접한 개념과 느슨한 개념을 표현한다.

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.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();
 }
 }
}

들여쓰기한 파일은 구조가 한눈에 들어온다.

가짜 범위

때로는 빈 while 문이나 for문을 접한다.이런 구조는 좋지 못한다. 또는 새미콜론은 새 행에다 제대로 들여써서 넣어준다.

while (dis.read(buf, 0, readBufferSize) != -1)
;

팀 규칙

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

팀은 한 가지 규칙에 합의해야 한다.그리고 모든 팀원은 그 규칙을 따라야 한다.

좋은 소프트웨어 시스템은 읽기 쉬운 문서로 이뤄진다는 사실을 기억하기 바란다. 스타일은 일관적이고 매끄러워야 한다. 한 소스 파일에서 봤던 형식이 다른 소스 파일에도 쓰이리라는 신회감을 독자에게 줘야 한다. 온갖 스타일을 뒤겄어 소스 코드를 필요 이상으로 복잡하게 만드는 실수는 반드시 피한다.

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

[Clean Code] 9장 단위테스트  (2) 2022.09.23
[Clean Code] 6장 객체와 자료구조  (0) 2022.09.22
[Clean Code] 4장 주석  (0) 2022.09.20
[Clean Code] 3장 함수  (0) 2022.09.19
[Clean Code] 2장 의미 있는 이름  (2) 2022.09.17

+ Recent posts